delete
delete

Reputation:

How can I instantiate a class using the shorthand C# way?

This is the class I'm trying to instantiate:

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'm trying to create it:

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

I remember I used to be able to do something like this before, how can I instantiate an object by giving it values up front in the single line? Thanks!

Upvotes: 5

Views: 12890

Answers (3)

Richard Cook
Richard Cook

Reputation: 33109

Use the object initializer syntax:

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

or even:

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

This relies on X and Y having public setters.

Upvotes: 21

Erik K.
Erik K.

Reputation: 1062

Actually, you can do without the empty brackets:

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

Upvotes: 2

Jackson Pope
Jackson Pope

Reputation: 14660

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

Upvotes: 1

Related Questions