Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut when creating a new class in C#

Tags:

c#

Is it possible to clean up the following code in any way?

This is what I use in my code:

var _index = new IndexViewModel();
_index.PageMeta = new PageMeta();
_index.Que = new Q();
_Index.Test = new T();

This is my class definition:

public class IndexViewModel {
   public PageMeta PageMeta { get; set; }
   public T Test { get; set; }
   public Q Que { get; set; }
}

I'm trying to remember if there's a shortcut when declaring a new class. Would it be possible for me to put something in the constructor of IndexViewModel ?

like image 580
Jonathan S Avatar asked Jan 20 '26 19:01

Jonathan S


2 Answers

Well, you could use an object initializer:

var _index = new IndexViewModel 
{
    PageMeta = new PageMeta(),
    Que = new Q(),
    Test = new T()
};

Which might not be much of a shorcut but does save you some bit of repetitive code.

EDIT to clarify question on comment

public class IndexViewModel {

   // The default constructor now initializes de values:
   public IndexViewModel() 
   {
       PageMeta = new PageMeta();
       Q = new Q();
       T = new T();
   }

   public PageMeta PageMeta { get; set; }
   public T Test { get; set; }
   public Q Que { get; set; }
}

If you add initialization to the constructor you don't need to use an object initializer anymore:

var _index = new IndexViewModel(); //<- initialized by its own constructor
like image 93
Sergi Papaseit Avatar answered Jan 23 '26 08:01

Sergi Papaseit


You could easily add a constructor that creates each of those new objects by default:

public class IndexViewModel {
   public IndexViewModel() {
       PageMeta = new PageMeta();
       Q = new Q();
       T = new T();
   }
   public PageMeta PageMeta { get; set; }
   public T Test { get; set; }
   public Q Que { get; set; }
}

Then when you need a new IndexViewModel with a new one of each of those objects, just call

new IndexViewModel()
like image 23
Jared Updike Avatar answered Jan 23 '26 07:01

Jared Updike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!