assignment of values to compound classes C #

0

I have the following problem, which may seem a bit silly, but I do not give with the answer. I have the next class

public class miClase
{ 
  public int miId {get; set;}
  public string miString {get; set;}
  public tipo1 miTipo1 {get; set;}
}

luego tengo otra clase tipo1
public class tipo1
{
  public int idTipo1 {get; set;}
  public string stTipo1 {get; set;}
}

when instantiating the type1 class, I can assign values to it in the following way

tipo1 t1 = new tipo1();
t1.idTipo1 = 1;
t1.stTipo1 = "hola";

per when instantiating the class myClass, I can not assign values to the variables of type1

miClase mc = new miClase();
mc.miId = 1;  // se puede
mc.miString = "chao"; //tambien se puede
mc.tipo1.idTipo1 = 2; // me da un mensaje de null reference
mc.tipo1.stTipo1 = "esto no vale"; // supongo que tb me da el mismo error

What am I doing wrong? Can not assign values directly to the class in this way? must we necessarily instantiate a variable type1, assign values to it, and then assign it to myClass?

Greetings

    
asked by Luis Gabriel Fabres 10.03.2017 в 21:17
source

2 answers

0
miClase mc = new miClase();
mc.miId = 1;  // se puede
mc.miString = "chao"; //tambien se puede
mc.tipo1.idTipo1 = 2; // me da un mensaje de null reference
mc.tipo1.stTipo1 = "esto no vale"; // supongo que tb me da el mismo error

type1 is the class, the object is myType1, that is, you will not be able to declare directly by calling the class To work for you, you should create the class myClass in the following way

    public class miClase
    { 
      public int miId {get; set;}
      public string miString {get; set;}
      public tipo1 miTipo1 = new tipo1();
    }

And in the assignment of variables

        miClase mc = new miClase();
        mc.miId = 1;
        mc.miString = "chao";
        mc.miTipo1.idTipo1 = 2; 
        mc.miTipo1.stTipo1 = "esto no vale";

Greetings

    
answered by 10.03.2017 / 21:38
source
1

What the error tells you is that no object has been defined for class tipo1 in class mc . If you can not touch the properties of miClase to make an automatic instantiation as proposed in another answer, you can create it manually using new like any other object:

miClase mc = new miClase();
mc.miId = 1;  // se puede
mc.miString = "chao"; //tambien se puede
mc.tipo1 = new tipo1(); // se crea un nuevo objeto de tipo1 en la variable mc
mc.tipo1.idTipo1 = 2; // esto no debería darte ya ningún mensaje de null reference
mc.tipo1.stTipo1 = "esto vale"; // y este tampoco debería darte ningún error

You can also use the short format indicated in another comment:

mc.miTipo1 = new tipo1 {idTipo1 = 2, stTipo1 = "esto vale"};
    
answered by 18.03.2017 в 14:09