Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, How to simply change order of class members

Tags:

c#

.net

class

Hi I Have a class derived from another class . Like this :

public  class Customer
  {
    public string Date{ get; set; }
    public string InstallationNo{ get; set; }
    public string SerialNo { get; set; }        
  } 

Then I have created a class named Customer_U which derived from Customer

 public  class Customer_U:Customer
  {
    public string Bill{ get; set; }            
  }  

I have simple question. I have google many time but no answer. I have list filled with data like:

List<Customer_U> customer= new List<Customer_U>() I create a excel using this list. In excel colum order is like this :

Bill --- Date --- InstalltionNo --- SerialNo.

Idont want this order. I want "Bill" member to be last columns . How to set order of member when createin a class derived from another class

like image 912
Noyan El Avatar asked Aug 25 '15 11:08

Noyan El


1 Answers

There is no defined order in a CLR class; it is up to the implementation that is inspecting the metadata of the class to determine how a class is interpreted.

For example, your Excel library is probably using reflection to inspect the class you pass it and reflection makes no guarantees as to the order in which things are processed.

Other implementations such as the WCF DataContractSerializer or ProtoBuf.NET handle order through the use of DataMember.

That said, if your library can handle dynamic or anonymous types then you can use the approach detailed in the other answers. .NET seems to consistently reflect these types in the same order that they were created.

var x = new { Z = "", Y = 1, X = true };
Console.WriteLine(x.GetType().GetProperties().Select(y => y.Name));

However it should be noted that this is an implementation detail and should not be relied upon. I'd see if you library allows you to specify the mapping between properties in your class and columns in your spreadsheet otherwise you might run into weird bugs in the future!

like image 155
Dean Ward Avatar answered Oct 09 '22 16:10

Dean Ward