member variables of Types without default constructor

  • Thread starter Thread starter LK
  • Start date Start date
L

LK

Why wouldn't c# catch the following problem at compile
time (as C++ does)?

class EmbClass
{
public int TestVar;
public EmbClass( int i )
{
TestVar = i;
}
}


struct ComplexStruct
{

/* **************PROBLEM************

Not saying here that EmbClass does not have a default
constructor!
*/
public EmbClass DefaultsHow;
public int m_j;
}

static void Main( )
{
ComplexStruct CS = new ComplexStruct( );

//correctly throws a Null-Reference exception
int i = CS.DefaultsHow.TestVar;
}
 
Why wouldn't c# catch the following problem at compile
time (as C++ does)?

Because it's usually not a problem. And C++ classes have different
semantics than managed classes (they are more like value types).

You get a NullReferenceException because the DefaultHow member hasn't
been assigned an object reference. That has little to do with the fact
that the EmbClass lacks a default constructor, since there are many
other ways you could get a valid EmbClass object reference.



Mattias
 
LK said:
Why wouldn't c# catch the following problem at compile
time (as C++ does)?

Because C++ needs an actual instance; C# only needs a reference, and
the default value of the reference is null. In other words, C++ would
create an instance in ComplexStruct, but C# wouldn't even if there were
a parameterless constructor.
 
Back
Top