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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With