Search Unity

structs in c#?

Discussion in 'Scripting' started by Wasiim, Jul 26, 2015.

  1. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    I am in Visual Studio but this code should be easy to consume. In the first example i can access clearInfo() no problem but why can't i access clearInfo() in the second example? i would appreciate answers.


    Code (CSharp):
    1. namespace ConsoleApp.day1.Example
    2. {
    3.      struct demo
    4.     {
    5.         public  int maxHitPoints;
    6.    
    7.         public demo(int hp)
    8.         {
    9.             maxHitPoints = hp;
    10.         }
    11.         public void clearInfo()
    12.         {
    13.             maxHitPoints = 0;
    14.         }
    15.    
    16.     }
    17.     class ExampleOne
    18.     {
    19.    
    20.         static void Main()
    21.         {
    22.  
    23.            demo dem1 = new demo(20);
    24.            dem1.clearInfo();
    25.            Console.WriteLine("The max hitpoint is {0}",dem1.maxHitPoints);
    26.         }
    27.     }
    28. }
    Code (CSharp):
    1. namespace ConsoleApp.day1.Example
    2. {
    3.     struct demo
    4.     {
    5.         public  int maxHitPoints;
    6.    
    7.         public demo(int hp)
    8.         {
    9.             maxHitPoints = hp;
    10.         }
    11.         public void clearInfo()
    12.         {
    13.             maxHitPoints = 0;
    14.         }
    15.    
    16.     }
    17.     class ExampleOne
    18.     {
    19.    
    20.         static void Main()
    21.         {
    22.  
    23.            demo dem1;
    24.            dem1.clearInfo();
    25.            Console.WriteLine("The max hitpoint is {0}",dem1.maxHitPoints);
    26.         }
    27.     }
    28. }
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Because in the second example, dem1 is hasn't been initialized yet, and ClearInfo() isn't a static function- it needs an actual object to call the function.
     
  3. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    so you need actual object to call functions but you don't need actual objects to use the variables?
     
  4. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    The variable is like a parking spot. Just because the spot exists doesn't mean you've parked a car in there yet, and you can't call OpenDoor() on an empty parking spot.

    EDIT: Misunderstood what you meant by "variable" there maybe as I thought you meant dem1 as a whole. No, if the struct hasn't been created yet, then you can't use the members (variables) or methods that are "supposed" to exist in it- it's just a big empty space where an object might go later.
     
  5. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    I don't quite get that analogy.
     
  6. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    I thought the same thing at first but i tried this in visual studio earlier and it worked. It can access the variables but for some reason i can't access the function clearInfo()
    Code (CSharp):
    1. namespace ConsoleApp.day1.Example
    2. {
    3.     struct demo
    4.     {
    5.         public int maxHitPoints;
    6.    
    7.         public demo(int hp)
    8.         {
    9.             maxHitPoints = hp;
    10.         }
    11.         public  void clearInfo()
    12.         {
    13.              maxHitPoints = 0;
    14.         }
    15.      
    16.     }
    17.     class ExampleOne
    18.     {
    19.    
    20.         static void Main()
    21.         {
    22.             demo dem1;
    23.             dem1.maxHitPoints = 15;
    24.            Console.WriteLine("The max hitpoint is {0}",dem1.maxHitPoints);
    25.         }
    26.     }
    27. }
     
  7. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Is there some particular reason why you're seeming to try and avoid initializing it like normal? Just say "demo dem1 = new demo();" Also, how are you figuring out that you can't access clearInfo()? Is there an error or are you basing that on the value output by maxHitPoints?
     
  8. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    The value output to the console shows maxHitPoints as 15 in the script above. There is not a particular as to why i'm doing this. I am just interested in this occurrence. Yes there would be an error if i were to access clearInfo() without creating an object i would get the error of use of unassigned local variable dem1 but that is not the case when i access a variable in dem1.
     
  9. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Okay, so apparently structs work a little differently than I thought. Even if you don't specify "new", it will auto-initialize it to a default state using the implicit parameterless constructor. The problem is that until all fields have been assigned, you can't access properties or methods for the struct in question. That means that just by assigning maxHitPoints = 0, you should then be able to call the function like normal.

    Very interesting.
     
  10. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    Yes the default state of the fields are null until you have assigned them just as you mentioned.
     
  11. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    I just watched a vid on this very interesting, and you can actually call a function in a struct after all the variables have been initialized.
     
  12. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    Sorry for the barrage of replies but i just want to make something clear. The "new" keyword does not make "something"(for lack of a better word) an object.

    What the new keyword does:
    • it allocates memory on the heap (this only applies to reference types)
    • constructors are invoked immediately after memory is allocated if you do not provide a constructor for your object or the constructor is a private one. C# compiler will create a default constructor which sets member values to their defaults(zeros everything out so stuff is not null)
    • constructors that take no paramaters are called default-constructors. You can make your own default constructors. This wont work with constructors of a struct because they cannot be parameter-less unless it's a default one made by the compiler
    • When it comes to structs you have to use the new keyword if you want to utilize it's automatic default constructor but please note a default constructor takes no parameters whatsoever
    Value types:
    • value types such as structs and primitive types are created on the stack so the "new" keyword is not necessary unless you want to initialize members of a struct in a constructor or set the member values to their defaults
    • all value types have a default value https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

    The following will produce an error:
    Code (CSharp):
    1.  
    2. int i;
    3. Console.WriteLine(i);
    4.  
    To fix this you do:
    Code (CSharp):
    1.  
    2. int i = new int();
    3. Console.WriteLine(i);
    4.  
    This is a great example as to why you would use the new keyword albeit unecessary.
     
    Last edited: Jul 27, 2015
  13. Mabenan

    Mabenan

    Joined:
    Feb 7, 2014
    Posts:
    132
    or you just write

    Code (CSharp):
    1. int i = 0;
    2. Console.WriteLine(i);
    like a normal c# programmer.
     
  14. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    That's exactly what I said. You even quoted me saying it in this very post. *shakes head*

    You really need to just use the "new" keyword anyways- it's like not putting "f" on your float values in the few instances you can get away with not doing so. There's no real point in not doing it, and it'll get you in trouble at some point if you make a habit of flaunting the exceptions.

    Indeed.
     
    Last edited: Jul 27, 2015
  15. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    "dem1 is hasn't been initialized yet, and ClearInfo() isn't a static function- it needs an actual object to call the function"
    Before you were implying you have to do demo dem1 = new demo() in order to be able to call the function which is false and demo dem1 is already an object. Plus you can call function clearInfo() with just demo dem1 you just have to initialize your variables before you do it. I don't know why you comment on me making a habit of not utilizing the new keyword. When i told you previously "There is not a particular as to why i'm doing this. I am just interested in this occurrence" but you should be able to recognize what is a object and what is not considered a object. At the end of the day there is no way you can say that's exactly what you said.
     
    Last edited: Jul 27, 2015
    DonLoquacious likes this.
  16. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    I quoted a post in which you were explaining how all you had to do was initialize all of the fields. You quoted me, in that same post, as having said the exact same thing, but didn't appear to notice. That was the reference that I was referring to. Calm down dude, no one's attacking you, I just thought it was amusing.

    Indeed, I did not know how structs were treated when this thread started- I admit that I use them only when I have to, like built-in rects and vectors. All of this has been fascinating, in a "more knowledge never hurts" kind of way, and as a way of diagnosing the numerous problems that likely occur from this unintuitive usage. Like the conditional operator though, I'm putting this in the "interesting, but never do it" category.

    *shrugs* Moving on.
     
  17. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    That was just as an example, at the end i did mention it was unecessary. No need to clarify that.
     
  18. X_datel_X

    X_datel_X

    Joined:
    Aug 7, 2020
    Posts:
    1
  19. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Can you provide an example?
     
    Nefisto, MelvMay, eisenpony and 2 others like this.