Search code examples
c#frameworksgame-engine

Modulate a check and cast to value


I am a beginner developer at C#, and have come across a rather unusual problem. Now, while my code currently is working as expected, I was hoping there is a better way to implement it. The code in question is within the ForEach of my list. The two example classes inherit Example. I was hoping that there is a better way to check and perform the following code in a more reusable way (method), since I use such checks and application elsewhere in my code.

public interface Example
{
    // some stuff
}

public class Something
{
    public List<Example> keybind ... // instantiate

    public Something()
    {
        keybind.ForEach(b =>
        {
            // these checks are what I want to reuse
            if (b.GetType() == typeof(Example1)
                (b as Example1).Value = // new value
            if (b.GetType() == typeof(Example2)
                (b as Example2).Value = // new value
        }
    }
}

Solution

  • Don't do the checks at all then - that's what interfaces are for. If you define that in your interface there is a property Value then any class that implements that interface will need to implement that property as well in turn removing the need to cast at all.

    public interface Example
    {
        string Value { get; set; }
    }
    
    public class Something
    {
        public List<Example> keybind... // instantiate
    
        public Something()
        {
            keybind.ForEach(b =>
            {
                b.Value = // new value
            }
        }
    }
    

    If you do need to check the type, then your syntax is right, the nicer alternative I could suggest is below (part of C# 7.0):

                if (b is Example1 ex1)
                {
                    //do stuff
                }