How can I use the same properties and methods on different classes?

2.3k views Asked by At

I have 3 class like ClassVersion1, ClassVersion2 and ClassVariables. ClassVariables is for reach variables of other class from Form.

İn my opinion were these;

if(version == 1)
{
    ClassVersion1 clss = new ClassVersion1();
}
else
{
    ClassVersion2 clss = new ClassVersion2();
}
clss.vars.variable1 = 3;
clss.vars.variable2=5;
clss.DoSomething();

But I have to call functions and variabless into the if condition(two objects with same name, different class). I want to Create object into condition and use out of condition.

How can I do this?

1

There are 1 answers

2
CodeCaster On

You could use an interface:

public interface IVersionedClass
{
    int Variable1 { get; set; }
    string Variable2 { get; set; }
}


public class ClassVersion1 : IVersionedClass
{
    public int Variable1 { get; set; }
    public string Variable2 { get; set; }
}

public class ClassVersion2 : IVersionedClass
{
    public int Variable1 { get; set; }
    public string Variable2 { get; set; }
}

Then use it like this:

IVersionedClass myClass;
if(version == 1)
{
    myClass = new ClassVersion1();
}
else
{
    myClass = new ClassVersion2();
}