Home > Software design >  Use the Same variable for "if is Class" condition for two different derived Classes
Use the Same variable for "if is Class" condition for two different derived Classes

Time:06-02

I have a base interface:

public interface IKlarfDefect
{
    int TEST { get; set; }
    int DEFECTID { get; set; }
}

Which fathers these two classes:

    public interface IKlarfDefect
{
    int TEST { get; set; }
    int DEFECTID { get; set; }

    public List<RMTKlarfImageListInfo> KlarfImageList { get; set; } = new List<RMTKlarfImageListInfo>();
}


public class CIMKlarfDefect : IKlarfDefect
{
    public int TEST { get; set; }
    public int DEFECTID { get; set; }

    public List<CIMKlarfImageListInfo> KlarfImageList { get; set; } = new List<CIMKlarfImageListInfo>();
    
}

I have a function that goes through a list of IKlarfDefect:

internal static string CreateDefectListString(IEnumerable<IKlarfDefect> klarfDefectList)
{
    StringBuilder defectListString = new StringBuilder();
    defectListString.AppendLine("");
    foreach (var klarfDefect in klarfDefectList)
    {    
        if ((klarfDefect is CIMKlarfDefect klarfDefectGeneric || klarfDefect is RMTKlarfDefect klarfDefectGeneric) ) 
        {
            if (klarfDefectGeneric.KlarfImageList.Count == 0)
            {
                defectListString.Append("N;");
                defectListString.AppendLine();
            }

        }
    }
    
}

But Visual studio gives me the error:

Severity    Code    Description Project File    Line    Suppression State
Error   CS0128  A local variable or function named 'klarfDefectGeneric' is already defined in this scope

Is there any way for me to use the same variable "klarfDefectGeneric" name for both types inside that if condition?

CodePudding user response:

Is there any way for me to use the same variable "klarfDefectGeneric" name for both types inside that if condition?

No there is no way to do that specifically.

But you can get the same functionality by creating another interface:

public interface IHasKlarfImageList
{
    List<Image> KlarfImageList{ get; }
}

Then inherit the interface in your two special classes:

RMTKlarfDefect : IKlarfDefect, IHasKlarfImageList

And now you can do this:

if ((klarfDefect is IHasKlarfImageList klarfDefectGeneric ) 
{
    if (klarfDefectGeneric.KlarfImageList.Count == 0)
    {
        defectListString.Append("N;");
        defectListString.AppendLine();
    }
}

Please be aware that if you find yourself doing something like if obj is type TypeA do X, else if obj is TypeB do Y you are violating the Open-Closed principle and failing to make proper use of polymorphism. Those are big words but the concepts are not as intimidating as they sound. Please save yourself (and the people you work with) a huge headache by building an understanding of those concepts. Polymorphism is the entire purpose of writing an interface in the first place.

  •  Tags:  
  • c#
  • Related