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

44,917

Solution 1

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.

Solution 2

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")
}
Share:
44,917
sgarcia.dev
Author by

sgarcia.dev

My Name is Sergei Garcia, and I’m a Front-End Engineer (and aspiring UI/UX designer) who loves to write high performance, clean, maintainable code for web apps. My hobbies include reading blogs to keep up to the latest trends in coding technologies and tech gadgets, taking courses about new Front End tool that help me stay ahead of the curve, as well as working on my next blog entry on Medium. I like to dabble in back end technologies like Node.js &amp; Python, because my next goal is to transition into a Full-Stack Developer.

Updated on July 09, 2022

Comments

  • sgarcia.dev
    sgarcia.dev almost 2 years

    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