-2

This question already was asked in severel variation.

Basicly it is : How to init a structure by the constant in C#?

Answer is - it is not possible in c#.

But... I can wrote

public class TModel2
{
    public const Int32 R32 = 32;
    public const Int32 R33 = 33;
}

[TestMethod]
public void TestMethod1()
{
    Int32 currentModel = TModel2.R33;
    switch (currentModel)
    {
        case TModel2.R32:
           break;
        case TModel2.R33:
           break;
    }
}

if I check a source of Int32 it's defined as a structure. I can easely repeat a code for Int32 and name it, for examle, TModelItem. All what I want is to wrote:

public class TModel1
{
    public const TModelItem R32 = 32;
    public const TModelItem R33 = 33;
}

[TestMethod]
public void TestMethod2()
{
    TModelItem currentModel = TModel1.R33;
    switch (currentModel)
    {
        case TModel1.R32:
            break;
        case TModel1.R33:
            break;
    }
}

But I can't get this working. Yes, TModelItem are repeat Int32 and code didn't even compile.

How do I make it work? Or What can be used to cover my needs? I need int or long int or string as a basis.

Murr
  • 52
  • 1

1 Answers1

0

Like in the comments already mentioned it's not possible.

I don't know if this fulfills your needs. But what you can do is something like this:

public readonly struct TModelItem
{
    public int Integer { get; }

    public TModelItem(int integer)
    {
        Integer = integer;
    }

    public static implicit operator TModelItem(int integer)
    {
        return new TModelItem(integer);
    }

    public static implicit operator int(TModelItem tModelItem)
    {
        return tModelItem.Integer;
    }
}
public class TModel1
{
    public static readonly TModelItem R32 = 32;
    public static readonly TModelItem R33 = 33;
}
[TestMethod]
public void TestMethod2()
{
    TModelItem currentModel = TModel1.R33;
    switch (currentModel)
    {
        case 32:
            break;
        case 33:
            break;
    }
}
nosale
  • 808
  • 6
  • 14