Tuesday, October 26, 2010

Structs

important differences that you should be aware of. First of all, classes are reference types and structs are value types.

By using structs, you can create objects

When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack.

Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance.

when passing a struct to a method, it's passed by value instead of as a reference.

Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct.

When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.

The only rule is that you need to initialize all fields of a struct before using it. You can do that by:

  • Create object by using new keyword.

  • calling an overloaded constructor. C# forces you to initialize all fields within every overloaded constructor, so there is no getting around the "initialize-everything" rule.

  • explicitly setting every field's value.

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class.

A struct can implement interfaces, and it does that exactly as classes do.

This example demonstrates struct initialization using both default and parameterized constructors.

This example demonstrates a feature that is unique to structs. It creates a Point object without using the newoperator. If you replace the word struct with the word class, the program won't compile.

For a reference type, readonly prevents you from reassigning a reference to refer to some other object. It does not prevent you from changing the state of the referred object.

For value types, however, readonly is like the constkeyword in C++, it prevents you from changing the state of the object. This implies that you can't reassign it again, as that would result in reinitialization of all fields. The following piece of code demonstrates that.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.