Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use a structure instead of a class to hold string only data in C#? [duplicate]

Tags:

c#

struct

C# question.
Say I have a customers class that has a bunch of props for storing string only data such as name postal data and phone numbers.

I don't use this entity for ORM as I'm only adding it to some type of collection for use during app life cycle. Additionally I don't need to add any entity specific methods to it or persist the data to xml or database, or even to a webservice.

Is it better to make this a struct rather than a class? or no benefit? Also side question, should I make the collection Customers, a list structure?

Be harsh, please critique.. :)

 struct customer
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }

struct Customers<List>
{
    private customer cust;

    public customer Cust
    {
        get { return cust; }
        set { cust = value; }
    }

}
like image 260
Anonymous Type Avatar asked Oct 25 '10 03:10

Anonymous Type


People also ask

When should I use a struct instead of a class?

Class instances each have an identity and are passed by reference, while structs are handled and mutated as values. Basically, if we want all of the changes that are made to a given object to be applied the same instance, then we should use a class — otherwise a struct will most likely be a more appropriate choice.

What is better class or structure?

There is no difference between classes and structs. Structs are classes; only default access is flipped from private to public.

When should I use struct in C?

You can use it to store variables in different types. The struct type is comparable to classes in object-oriented programming. Sometimes you may need to assign values to objects with the same properties. Instead of creating multiple variables for these objects in your C program, you can define them in a struct.

What is the advantage of structure over class?

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment.


2 Answers

I can't see any value in making the customer a struct. The string fields will all be reference types, so you might as well make the whole thing a reference type (ie. class).

I'd be inclined to use one of the built-in collection types rather than create my on type for Customers. Something like:

List<Customer> Customers = new List<Customer>();
like image 98
Andrew Cooper Avatar answered Oct 06 '22 10:10

Andrew Cooper


I suppose you could look at When to use struct in C#?

like image 30
Dynami Le Savard Avatar answered Oct 06 '22 10:10

Dynami Le Savard