C# console program questions regarding instantiation and use of static fields -


c# newbie here. took test asked out put of c# code was. don't have exact code i've tried recreate memory below. code doesn't compile reason(not important since have questions happening here). part had issues trying remember lines creating class fields.

here questions:

  1. is creating new instance of class using "new class1();" without assigning variable valid way instantiate it?
  2. each time class instantiated how static fields handled?
  3. can create class fields calling constructor?

    using system; using system.collections.generic;  namespace customfunctiontest {     class program     {         static void main(string[] args)         {             new class1();             new class1("e");          }     }     public class class1     {          public static class1 test1 = new class1("a");         private class1 b = new class1("b");         public static class1 c = new class1("c");          public class1()         {             console.writeline("d");         }         public class1(string str)         {             console.writeline(str);         }      } } 

1) creating new instance of class using "new class1();" without assigning variable valid way instantiate it?

yes. it's constructor perform action on static objects, or retained somehow. or, garbage collected. quality code? not usually.

2) each time class instantiated how static fields handled?

if there static constructor, static fields initialized before static constructor when type being initialized , type initialized once. in example, there no static constructor, runtime defers initialization if static fields until accessed.

3) can create class fields calling constructor?

yes. class's fields initialized when class constructed.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -