One of the types in .NET we haven’t talked about much is the struct.
struct is short for structure, and structs look a lot like objects.
They have fields and properties, just like objects. And you can even pass
them into a method that takes an object type parameter:
A struct looks like an object…
…but isn’t an object
public struct Dog {
public string Name;
public string Breed;
public Dog(string name, string breed) {
this.Name = name;
this.Breed = breed;
}
public void Speak() {
Console.WriteLine(“My name is {0} and I’m a {1}.”, Name, Breed);
}
}
But structs aren’t objects. They can have methods and fields, but
they can’t have finalizers. They also can’t inherit from other classes or
structs, or have classes or structs inherit from them.
Structs are best used for storing data, but the lack of inheritance and references can be a serious limitation.
But the thing that sets structs apart from objects more than almost anything else is that you copy them by value, not by reference. Which means values get copied; references get assigned.
When you create a struct, you’re creating a value type. What that means is when you use equals to set one struct variable equal to another, you’re creating a fresh copy of the struct in the new variable. So even though a struct looks like an object, it doesn’t act like one.
Comments
Post a Comment