Structs are whatâs called value types. Essentially, this means that when you pass them around, you pass a copy of the actual contents of the structs.
Classes, on the other hand, are reference types. This means that when you pass those around, you pass a pointer to the actual object, and no copying of anything happens.
The null value is a special value which means âthis reference points at nothingâ. Since structs are not references, it doesnât make sense to reference a struct type as null.
Now, this is awfully inconvenient - after all you often use null as a special value that signifies âthereâs nothing hereâ in your abstraction, and donât really think of it as a pointer. But, youâll have to live with it. Thereâs some solutions:
1: Turn your struct into a class. This will solve everything automatically for you, but remember that objects will have to be processed by the garbage collector. If youâre creating a large amount of these MovieItems (thousands), this might become a problem. Otherwise this is the easiest way to go about it.
As a general rule, if you have something that contains reference types (as opposed to only structs and primitives like integers), it should itself be a reference type, so Iâd go with using a class here as MovieTexture is a class.
2: Signify that thereâs no movie there in some other way. the usual way to do that would be to return default(MovieItem) instead of null. The default argument returns null for reference types, and a zero-value for structs. So wherever youâd check if the object returned was null, you check if itâs equal to default(MovieItem) instead:
public MovieItem GetMovieItemByName(string movieName){
for (int i=0; i<movies.Count; i++) {
if(movies[i].name == movieName){
return movies[i];
}
}
return default(MovieItem);
}
//usage:
MovieItem myMovie = movieDatabase.GetMovieItemByName("Spider Man 2");
if(myMovie == default(MovieItem) {
BeSad();
}
else {
WatchMovie(myMovie);
}
3: use a nullable struct. Whenever you define a struct named âSomeStructâ, the type âSomeStruct?â is a type that can either be a member of SomeStruct, or null. So your GetMovieItemByName method would look like:
public MovieItem? GetMovieItemByName(string movieName){ ... }
And you would be able to return null as much as you want. To get the actual MovieItem from the MovieItem?, thereâs a special .Value property you can use to get the actual movie:
MovieItem? myMovie = GetMovieItemByName("Spider Man 2");
if(myMovie == null) {
BeSad();
}
else {
WatchMovie(myMovie.Value);
Hope that helps!