C# - Struct doest not allow redifinition of the parameterless constructor

If you are familiar with the C# construct structure, than you may probably be familiar with the structure, while structure will group the members in continous memory, and it is more lightweight than classses and believes to create less fragment than the class (reference types).

    private struct CPSSOWDeleteTuple
    {
      public CPSMessage Data { get; set; }
      public CPSMessage Schema { get; set; }

      public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) 
      {
        Data = data;
        Schema = schema;
      }
 

There is somthing that you may not be very clear about the structure types. for one thing, since a struct cann not be empty, so the compiler will generate a default constructor so it can fit in many application situation such as the List<struct> or Map<...,struct>;

 

 

Let 's see one example, suppose we have a struct which is called CPSSOWDeleteTuple, and this tuple has two member, one represents a Data and the other represents a schema, and both the Data and the Schema are of the type of "CPSMessage";

 

 

 

   private struct CPSSOWDeleteTuple
    {
      public CPSMessage Data { get; set; }
      public CPSMessage Schema { get; set; }
   }
 

 

now, we want to provide some constructor which is not an void paramters list. if you directly do this: 

 

    private struct CPSSOWDeleteTuple
    {
      //... same as before

      public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) 
      {
        Data = data;
        Schema = schema;
      }
   }

 

 

you will get an error, basically it will say that "Backing field for autmatically implemented property '...Data' Must be fully initialized before control is returned to the caller. Consider calling the default constructor from a constructor initializer"....

 

it does not make much sense, but I do know somewhere to make clean of this error: here ist the modified version of the CPSSOWDeleteTuple.

 

public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) : this()
      {
        Data = data;
        Schema = schema;
      }

 

As you can see, you have to call the parameterless constructor in another constructor, then the compiler will stop complaining...

 

你可能感兴趣的:(C#)