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 ?
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With