Serve Laurijssen
Serve Laurijssen

Reputation: 9733

C# inner struct without new

Is the following code allowed? An inner struct is declared inside an outer class and new is not called for the struct. It does not crash but I got some doubt about it.

struct Inner
{
    public int i;
}

private class Outer
{
    public Outer() { inner.i = 10; }

    private int i;
    public Inner inner;
}

private static void Main(string[] arg)
{
    Outer o = new Outer();

    Console.WriteLine(o.inner.i);
}

Upvotes: 1

Views: 1159

Answers (2)

Matt
Matt

Reputation: 27001

The following is cited from MSDN and shows how Structs are different from classes (see the parts I've formatted in bold, they should answer your question):

"Structs share most of the same syntax as classes, although structs are more limited than classes:

  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct cannot declare a default constructor (a constructor without parameters) or a destructor.
  • Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • Structs are value types and classes are reference types.
  • Unlike classes, structs can be instantiated without using a new operator.
  • Structs can declare constructors that have parameters.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  • A struct can implement interfaces.
  • A struct can be used as a nullable type and can be assigned a null value."

Upvotes: 4

Boris Parfenenkov
Boris Parfenenkov

Reputation: 3279

Value types (structs are value types) automatically constructing with default value, therefore this code will be ok (if I correctly understand your question).

More about value type

Upvotes: 3

Related Questions