How can I instantiate a class using C # shortcut path?

This is the class I'm trying to create:

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { public class Posicion { public int X { get; set; } public int Y { get; set; } } } 

And here I am trying to create it:

 button1.Tag = new Posicion() { 1, 1 }; 

I remember that before I could do something like this, how can I create an instance of an object by specifying its values ​​in one line? Thanks!

+4
source share
3 answers

Use the object initializer syntax:

 button1.Tag = new Posicion() { X = 1, Y = 1 }; 

or even:

 button1.Tag = new Posicion { X = 1, Y = 1 }; 

It depends on X and Y having public setters.

+17
source

Actually, you can do without empty brackets:

 button1.Tag = new Posicion { X = 1, Y = 1 }; 
+2
source
 button1.Tag = new Posicion() { X = 1, Y = 1 }; 
+1
source

All Articles