views:

45

answers:

2

What I want to do is provide some public static fields that will be used as instances of an interface implementation and have intellisense pick them up when the interface is a method argument.

The idea is to have it look like an enum to the developer. I reference Color because basically this is the behavior I want, I just don't know how to replicate it.

Edit

I don't know what was going on. It seems to be working now. Thanks for the quick help on a stupid question.

+3  A: 

The Color struct simply has a bunch of public static properties that return the expected objects. Sample:

public struct Color 
{
    public Color(int r, int g, int b) 
    { /* Init */ }

    public static Color Black
    {
        get { return new Color( 0, 0, 0 ); }
    }
}

To clarify my answer. You would simply need to replicate this pattern within your own code to achieve the same affect. I'd recommend looking at the T4 code-gen built into Visual Studio if you have a lot of values that need to be created that already exist else-ware. Just don't add too many. That could confuse the developer and slow down the IDE.

chilltemp
Thanks, I knew it should be simple, but it wasn't working for some reason. Now it seems to be OK.
Robin Robinson
+2  A: 

You seem to have answered your own question when asking it - use public static fields:

public class MyClass
{
    public const string Value1 = "something one";
    public static readonly  MyType Value2 = new MyType();
    public const int Value3 = 3;
}

public class MyOtherClass
{
    public MyOtherClass()
    {
        string str = MyClass.Value1;
        // str == "something one"
    }
}
Oded
There is no such thing as "static const" in C#. Do you mean "static readonly" or just "const"?
Jesse C. Slicer
@Jesse C. Slicer - I corrected my answer before you posted your comment...
Oded
@Oded - I do see that. However, now the public fields are mutable and I could do `MyClass.Value1 = "something else!";` in `MyOtherClass`. I would recommend marking them as `const` instead of static if they're strings, `static readonly` for other reference types.
Jesse C. Slicer
@Jesse C. Slicer - good points. Answer amended.
Oded
@Oded - bravo, good sir.
Jesse C. Slicer
Making a complex object readonly does not affect its public properties. In the above example it would prevent me from changing the instance that Value2 contains, but it would not stop me from changing Value2.Something. The potentially dangerous thing is that the developers might not realize that changing Value2.Something affects every use of Value2.Something. Using a public property that returns new instances avoids this problem. That being said, always returning a new instance is not without expense. You should probably do a search for singleton patterns if you need this.
chilltemp