//CodeSample1 //declare class fileds but not initialize them. public class Cat {     public int Age;     public string Name; }  Cat aCat = new Cat();   Check the result, aCat.Age is 0, aCat.Name is null.  How the fields are initialized? The above code just declare fields and not initialize them.  If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values as listed in Default Values Table.(From )  So it's the compiler generated default constructor initialize fields. Is it right?  Changed Code, initialize fields when declare them.  //CodeSample2 //declare class fields and initialize them at same time. public class Cat {     public int Age = 4;     public string Name = "Black"; }  Cat aCat = new Cat();   This time the Result is that aCat.Age is 4, and aCat.Name is "Black".  I know the result is as expected. But do not understand how it works.  Fields are initialized immediately before the constructor for the object instance is called. (From )  Combine  and , CodeSample1 and CodeSample2 should have the same results (I know it strange).   My understanding is, in CodeSample2, firstly Age field is initialize to 4, then the compiler generated default constructor is called and set the age to default value (0).  Have I misunderstood the documents, or the documents are somewhat wrong?  If there are more accurate documents, please show me.
35959
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.  Should I do it at declaration?:  public class Dice {     private int topFace = 1;     private Random myRand = new Random();      public void Roll()     {        // ......     } }   or in a constructor?:  public class Dice {     private int topFace;     private Random myRand;      public Dice()     {         topFace = 1;         myRand = new Random();     }      public void Roll()     {         // .....     } }   I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.
38527
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the .  However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)  Here's an example:  class A(object):     _dict = dict()      def __new__(cls):         if 'key' in A._dict:             print "EXISTS"             return A._dict['key']         else:             print "NEW"             return super(A, cls).__new__(cls)      def __init__(self):         print "INIT"         A._dict['key'] = self         print ""  a1 = A() a2 = A() a3 = A()   Outputs:  NEW INIT  EXISTS INIT  EXISTS INIT   Why?
7189
I generate all my columns in a subclassed DataGridView programmatically. However Visual Studio 2008 keeps reading my constructor class (which populates a DataTable with empty content and binds it to the DataGridView) and generates code for the columns in the InitializeComponent method - in the process setting AutoGenerateColumns to false.  This causes errors in design-time compilation which are only solved by manually going into the design code and deleting all references to these autogenerated columns.  How can I stop it doing this?  I have tried:   Making the control 'Frozen' Setting the DataGridView instantiated object protected (suggested in a previous post which referred to )
53020
I have a question about default constructors and inheritance in Java.   Generally, if you write a class and do not include any constructor, Java provides automatically for you a default constructor (one without parameters), which initializes all instance variables of the class (if there are any) with some default values (0, null, or false). If you write a constructor, however, with some parameters, and you don't write  any default constructor, then Java does not provide a default constructor.  My question is: what is the case with classes, which inherit from other classes - if I write a constructor with some parameters in them, but don't include a default constructor, do they inherit the default constructor of the super class?
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
85933
I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.  Getting the field names is fairly simple, here is what a co-worker came up with:  public static List initFieldArray(String className) throws ClassNotFoundException {      Class c = Class.forName(className);     Field field[] = c.getFields();     List&lt;String&gt; classFields = new ArrayList(field.length);      for (int i = 0; i &lt; field.length; i++) {         String cf = field[i].toString();         classFields.add(cf.substring(cf.lastIndexOf(".") + 1));     }      return classFields; }   Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.  Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.
100509
I want to know about the setter and getter. I know that it is a properties of declaring variable but some time I get confused. Presently I am using a sample of code that is below:  public with sharing class hello {     public String temp{set;get;}      public hello(){         temp = 'first' ;     }      public String gettemp(){         return 'second' ;     } }   So I want to know that when I use temp on VFP than what value will show on page, what is reason for that, and what is the difference between temp and gettemp?  Thanks Ashlekh Gera
86767
Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?  For example, the following throws the error "A local variable named 'variable' is already defined in this scope".  switch (Type) {     case Type.A:             string variable = "x";                 break;     case Type.B:             string variable = "y";                 break; }   However, per the logic, the initial declaration should not be hit if the type is Type.B. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?
93507
In C#, is there a way to instantiate an instance of a class without invoking its constructor?  Assume the class is public and is defined in a 3rd party library and the constructor is internal.  The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.  NOTE: I specifically do not want to call any constructor so using reflection to access the internal constructor is not an option.
94519
Is it possible in c# to initialize an array in, for example, subindex 1?  I'm working with Office interop, and every property is an object array that starts in 1 (I assume it was originally programed in VB.NET), and you cannot modify it, you have to set the entire array for it to accept the changes.  As a workaround I am cloning the original array, modifying that one, and setting it as a whole when I'm done.  But, I was wondering if it was possible to create a new non-zero based array
27421
In C#, I want to initialize a string value with an empty string.  How should I do this?  What is the right way, and why?  string willi = string.Empty;   or  string willi = String.Empty;   or  string willi = "";   or what?
47651
I have three questions that I'd like to be clarified.   Is their anyway we could create Custom Metadata in Test Classes? I tried to create on my Test Class but I got an error saying the fields of the metadata could not be writable.  If not, then does that mean we should declare real values in our Custom Metadata and use that instead in our test classes? If (2) is correct, then does this mean we have to create the Custom Metadata in the environment we'll be deploying our code before doing the actual deployment?
77509
When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this  [MyAttribute("This code sux and should be looked at")] public void DoEverything() { }   &lt;MyAttribute("This code sux and should be looked at")&gt; Public Sub DoEverything() End Sub   I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.
87942
I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?
87888
I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constructor. For example:   public class Genotype {   private boolean bits[];   private int rating;   private int length;   private Random random;    public Genotype() {              //  &lt;= THIS is the bandit, this one right here     random = new Random();   }    /* creates a Random genetoype */   public Genotype(int length, Random r) {     random = r;     this.length = length;     bits = new boolean[length];      for(int i=0;i&lt;length;i++) {         bits[i] =random.nextBoolean();     }   }    /* copy constructor */   public Genotype(Genotype g,Random r) {     random = r;     bits = new boolean[g.length];     rating = g.rating;     length = g.length;      for(int i=0;i&lt;length;i++) {         bits[i] = g.bits[i];     }    } }   The first constructor doesn't seem to be a "real" constructor, it seems as though in every case one of the other constructors will be used. So why is that constructor defined at all?
58176
I was looking at C# collection initializers and found the implementation to be very pragmatic but also very unlike anything else in C#  I am able to create code like this:  using System; using System.Collections;  class Program {     static void Main()     {         Test test = new Test { 1, 2, 3 };     } }  class Test : IEnumerable {     public IEnumerator GetEnumerator()     {         throw new NotImplementedException();     }      public void Add(int i) { } }   Since I have satisfied the minimum requirements for the compiler (implemented IEnumerable and a public void Add) this works but obviously has no value.  I was wondering what prevented the C# team from creating a more strict set of requirements?  In other words why, in order for this syntax to compile, does the compiler not require that the type implement ICollection?  That seems more in the spirit of other C# features.
36269
In .NET why is String.Empty read only instead of a constant? I'm just wondering if anyone knows what the reasoning was behind that decision.