Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a Partial Class Object in C#?

I defined a class:

public class Sample{
    public string name {get;set;}
    public int price {get;set}
}

Then

 Sample sampleA = new Sample();
 sampleA.name = "test";

  Sample sampleB = new Sample();
  sampleB.price = 100;

I do this because I will save JSONed sampleA and JSONed sampleB to Azure table, to present a full sample object. In other code, sometime only need name, sometime only need price, so I only need to pull data that needed each time. Of course in real code, the structure of the sample is much much more complex.

My question is:, is there any easy method that can do:

  Sample sampleC = sampleA + sampleB;

and sampleC should contain:

 sampleC.name = "test";
  sampleC.price = 100;
like image 757
Eric Yin Avatar asked Dec 11 '11 17:12

Eric Yin


2 Answers

This has actually nothing to do with partial classes. Partial class is a single class, which is "geographically" declared more than in one file.

File1.cs:

public partial class File { public string Prop2 { get;set; } }

File2.cs:

public partial class File { public int Prop1 { get;set; } }

which will, when compiled, produce:

public partial class File 
{
     public string Prop2 { get;set; } 
     public int Prop1 { get;set; } 
}

For what you are asking.
There is no such method, which would combine two different instances into one. You should write it by your own.

UPDATE:
You may ask, why there is no such method. But how would it handle situation like:

Sample sampleA = new Sample();
sampleA.name = "test";
sampleA.price = 200;

Sample sampleB = new Sample();
sampleB.price = 100;

Sample sampleC = sampleA + sampleB; // what would be the value of price here: from sampleA or sampleB?
like image 65
Alexander Yezutov Avatar answered Sep 21 '22 22:09

Alexander Yezutov


How about you just overload the + operator ?

    public static Sample operator +(Sample left, Sample right)
    {
        left.price = right.price;
        return left;
    }
like image 45
Gabe Avatar answered Sep 22 '22 22:09

Gabe