sgarcia.dev
sgarcia.dev

Reputation: 6170

How to create a simple Object with properties in C# like with javascript

I'm working with Xamarin, and I need something that looks like this:

public Colors = new object() {
  Blue = Xamaring.Color.FromHex("FFFFFF"),
  Red = Xamarin.Color.FromHex("F0F0F0")
}

So I can later do something like this:

myObject.Colors.Blue // returns a Xamarin.Color object

But of course, this doesn't compile. Aparently, I need to create a complete new class for this, something I really don't want to do and don't think I should. In javascript, I could do something like this with:

this.colors = { blue: Xamarin.Color.FromHex("..."), red: Xamarin... }

Is there a C sharp thing that can help me achieve this quickly? Thank you

Upvotes: 29

Views: 80789

Answers (2)

musium
musium

Reputation: 3082

You could create a dynamic object (https://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject%28v=vs.110%29.aspx, https://msdn.microsoft.com/en-us/library/bb397696.aspx). But C# is a strongly typed language… not an untyped language like javascript. So creating a new class is the way to do this in C#.

Example using a dynamic Object:

public class Program
{
    static void Main(string[] args)
    {
        var colors = new { Yellow = ConsoleColor.Yellow, Red = ConsoleColor.Red };
        Console.WriteLine(colors.Red);
    }
}

Or using a ExpandoObject:

public class Program
{
    static void Main(string[] args)
    { 
        dynamic colors = new ExpandoObject();
        colors.Red = ConsoleColor.Red;
        Console.WriteLine(colors.Red);
    }
}

Or the more C# OO way of doing this…. create a class:

public class Program
{
    static void Main(string[] args)
    { 
        var colors = new List<Color>
        {
            new Color{ Color = ConsoleColor.Black, Name = "Black"},
            new Color{ Color = ConsoleColor.Red, Name = "Red"},
        }; 
        Console.WriteLine(colors[0].Color);
    }
}

public class Color
{
    public ConsoleColor Color { get; set; }
    public String Name { get; set; }
}

I recommend using the last version.

Upvotes: 38

yyny
yyny

Reputation: 1736

Sometimes Google is your best friend:

https://msdn.microsoft.com/en-us/library/bb397696.aspx

var Colors = new {
    Blue = Xamaring.Color.FromHex("FFFFFF"),
    Red = Xamarin.Color.FromHex("F0F0F0")
}

Upvotes: 8

Related Questions