Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 713
sgarcia.dev Avatar asked May 18 '15 22:05

sgarcia.dev


1 Answers

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.

like image 99
musium Avatar answered Oct 11 '22 12:10

musium