Linking two objects of different classes, but with similar properties

Is it possible in C # to link two objects of different classes but with similar properties?

Example:

class Program
{
    static void Main(string[] args)
    {
        test t = new test();

        test2 t2 = new test2();
    }
}

public class test
{
    public int Number { get; set; }
}

public class test2
{
    public int Number { get; set; }
}

      

So can you somehow say t = t2

?

+3


source to share


2 answers


You can use both classes for an interface if you don't need an interface implementation.

For example:

class Program
{
    static void Main(string[] args)
    {
        INumber t = new test();

        INumber t2 = new test2();
    }
}

public class test : INumber
{
    public int Number { get; set; }
}

public class test2 : INumber
{
    public int Number { get; set; }
}

public interface INumber
{
    int Number { get; set; }
}

      



An interface is a kind of contract that defines what properties and methods an implementation class should define. You can read more about interfaces here .

When your classes implement a common interface, you can implicitly convert from one type to another, such as in the example above.

+2


source


Without adding extra code, no, you can't do that.

Even though they are "similar", they are compiled as completely different types and cannot be assigned to each other.

You can now enable the operator implicit

on one (or both) to allow implicit casting in between.



public class test
{
    public static implicit operator test(test2 t)
    {
        return new test(tt.Number);
    }

    public static implicit operator test2(test t)
    {
        return new test2(t.Number);
    }

   public int Number { get; set; }
}

      

But this is as close to supporting this syntax as possible.

0


source







All Articles