Note that there are some explanatory texts on larger screens.

plurals
  1. PONot Understanding Object Instantiation in C#
    primarykey
    data
    text
    <p>This post goes to a gap in my understanding of C# classes and why they are preferable to static functions.</p> <p>I am trying to get a List of objects. Each object in the list represents a record in a table. This would be easy to do in a static function. </p> <p>Using a class, I've been able to do it as follows:</p> <p>Calling routine:</p> <pre><code>ListOfBusinesses l = new ListOfBusinesses (); List&lt;Business&gt; b = l.listBusinesses(); </code></pre> <p>The classes:</p> <pre><code> public class Business { public string Bupk { get; set; } public string Bu_name { get; set; } } public class ListOfBusinesses { public List&lt;Business&gt; listBusinesses() { List&lt;Business&gt; businesses = new List&lt;Business&gt;(); businesses.Add(new Business("1", "Business Name 1")); businesses.Add(new Business("2", "Business Name 2")); return businesses; } } </code></pre> <p>Couldn't I rewrite the class so that this could be done with one line:</p> <pre><code>ListOfBusinesses l = new ListOfBusinesses(); </code></pre> <p>It seems to me like the ListofBusinesses class above is nothing but a static function wrapped in a class which has no properties and is only there for the sake of having a class.</p> <p>I tried:</p> <pre><code>public class ListOfBusinesses { List&lt;Business&gt; businesses; public List&lt;Business&gt; ListOfBusinesses() { List&lt;Business&gt; businesses = new List&lt;Business&gt;(); businesses.Add(new Business("1", "Business Name 1")); businesses.Add(new Business("2", "Business Name 2")); return businesses; } } </code></pre> <p>But received the compiler error "member names cannot be the same as there enclosing type". Eg, I tried to use a constructor, but am missing something.</p> <p>Any help would enlighten me in an area I have misunderstood for some time.</p> <p>Mike Thomas</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload