27

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

PetoMPP
  • 78
  • 10
sgarcia.dev
  • 5,671
  • 14
  • 46
  • 80
  • 1
    Well 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#. – musium May 18 '15 at 22:42
  • Can you post this an answer so I can mark it as accepted when I get home and test this works on my code (which I think it will, or I think...) – sgarcia.dev May 18 '15 at 22:49

2 Answers2

37

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.

musium
  • 2,942
  • 3
  • 34
  • 67
  • Worth noting: with the advent of C# 7, you can return Tuples with named items as detailed in [this answer](https://stackoverflow.com/a/36436255/5403341). This lets you return something like the first dynamic object in this answer from a function, if you like. – Ben Seymour Dec 23 '20 at 21:45
8

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")
}
yyny
  • 1,623
  • 18
  • 20
  • I don't think that works. How can I create a new "Blue" if Blue doesn't exist as a class? – sgarcia.dev May 18 '15 at 22:47
  • 4
    It works...blue is just the name of the property the type is given from the right side. Try: var colors = new { Blue = ConsoleColor.White, Red = ConsoleColor.Red }; – musium May 18 '15 at 22:50
  • @NathanCooper The above code might not compile (Because I dont have a C# compiler at the moment) but Google and Microsoft defenitly are a better way of finding information than testing until it works. @musium I will edit the answer to use var instead, didn't really look through the microsoft site :| @sgarcia you are not creating `new Blue();`s you are not even creating new `Xamarin.Color`'s. All you are doing is putting objects in a parent object, just like how javascript works. (there is no such thing as a `new {}`; in javascript, you just put in existing variables: {x: 5} does work.) – yyny May 18 '15 at 22:58
  • Now your code does compile, but is a local variable that cannot be returned from the scope is in declared in in a typesafe manner. It also cannot be set as a member of a class. It really does depend on what the OP means by "later", but this isn't going to be the right approach for variables needed after the method scope `colors` was declared in is exited. ("Compilers enforce understanding" was nonsense of course, but I'm still a big fan of them, there's even a great .NET one online: https://dotnetfiddle.net/) – Nathan Cooper May 18 '15 at 23:08
  • @YoYoYonnY Just for the record. There is a new key word in javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new But you’re right no new object (expect the parent object) gets created in your code. – musium May 18 '15 at 23:09
  • @musium Yeah... What I ment to say was: In Javascript `{x: 5}` is equal to `new {x = 5};` in C#. And in neither cases, it makes sense to use `{x: new Number(5)}` (Does this work?) or `{x = new int(5)}` when you are not using the reference of the variable. It doesn't make sense to use the reference of a int either way. I also don't know why anonymous types can't be fields... Because the size of a anonymous type is always the same. – yyny May 18 '15 at 23:18
  • @YoYoYonnY 1) It works. 2) They can be used… but the only thing the compiler knows about such a field is that it is typeof object… which means you can’t access the properties without any casting etc. – musium May 18 '15 at 23:23
  • @musium I was talking about `public var x = new {y = 5};` (Okay, maybe `var` is not the right keyword to use here...) The size of x will always be the size of y, so I don't get why x can't be a class member in this case. I was thinking maybe it had to do with the fact that a class member is not final (constant)? But using `const` doesn't work either, so I really dont get why anonymous objects can't be class members... To me `var x = new {};` is more like a namespace like it is in javascript. But Im not really a C# pro tho :) – yyny May 18 '15 at 23:33
  • My bad, I read the code so fast I didn't see Blue was being set up as a property. Thanks musium – sgarcia.dev May 18 '15 at 23:35