Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Basic things that I just don't understand 4

Status
Not open for further replies.

Henk1

Programmer
Oct 26, 2001
46
ZA
Good day,

I have a couple of basic concepts that I just don't understand. Maybe you can explain it to me?

1. Get and Set on a property
2. Struct

Why would you want to use get and set? What does it do?
What is a struct and why does it get used?

Thanks alot for all the help.
 
1) The get/set properties are an easier way of calling functions. And it helps to solidify the idea of an "object"

For instance, you may have an object called "Human", with properties, Height, Weight. But you can also call functions Walk(), Run(). It is better to have a property for Height + Width, rather than call functions called SetHeight().

An example in C# might be:

namespace PropertyTest
{
public class Human
{
private int m_iHeight = 0;
private int m_iWeight = 0;

public Human()
{
}

public int Height
{
get
{
return m_iHeight;
}
set
{
m_iHeight = value;
}
}

public int Weight
{
get
{
return m_iWeight;
}
set
{
m_iWeight = value;
}
}

public void Walk()
{
// Do stuff here to make him walk
}

public void Run()
{
// Do stuff here to make him run
}
}
}


If you created a new class of Human:

Human MyHuman = new Human();

You can do the following new things:
MyHuman.Height = 200;
MyHuman.Weight = 300;
MyHuman.Run();

int iHeight = MyHuman.Height;
int iWeight = MyHuman.Weight;

that help?

/////////////////////////////////////////////

2) A struct is a method of enclosing data in a STRUCTure. Although normally you would use it in a C environment, in C# and C++ you would normally just create a class. A struct can contain many different variables for instance:

struct MyStruct
{
int Height;
int Width;
}

But it cannot contain functions like a class can (except function pointers - but thats an entirely different subject!!)



Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
Beautiful...

So I can then just set the value of height and weight of the instance of my classby using:
MyHuman.Height = 200;
MyHuman.Weight = 300;
?

Good stuff.

So you would normally not use a struct? What would you use it for then? Or could you in all cases just use a class?
 
yes thats exactly how you could use properties. It seems classes and C# structs share many common aspects including being able to call functions which i didnt realise. The paragraph was interesting:

"When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference. "

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
Get and Set:
They are also useful in other places.
1. read only
class A
{
private int m_data;
public A(int data)
{
m_data = data;
}
public int Data
{
get{ return m_data };
}
}
Now u can only read this property and can't set it's value after it was initialized.
2. index mark
class A
{
private int[] m_data;
public A()
{
m_data = new int[4];
}
public int this[int index]
{
get{ return m_data[index]; }
set{ m_data[index] = value; }
}
}
void main()
{
A a = new A();
a[3] = 4;
}
Now u can use index mark directly with object.
 
struct:
Struct type is value type as class type is reference type.
a direct example of difference between value type and reference type lies in parameters to a method :(my poor eng
class A {}
struct B {}
public void method1(A par) // transfer the reference
public void method2(B par) // transfer the real value by creating a copy
 
One reason to choose to use a class over a struct is if you plan on putting the object into a collection. If you use a struct, it will need to be "boxed" (turned into a reference object from a value object). This takes more memory than writing it as a class originally, plus accessing it is very slow as the CLR has to cast it back into a struct prior to use.

Another good reason to use getters & setters (versus allowing public access to the member variables themselves) is to enforce business rules. If you have a salaryHigh and salaryLow, you want to make sure that the High is higher than the Low value. You can't enforce this if the member variables are public, but you can in your property setter.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Thanks for all the replies. This is why I post on this forum, and recommend it to all the IT ppl I know.

ChipH, you said :

"You can't enforce this if the member variables are public, but you can in your property setter."

Can you explain this to me in more detail please? Why can you and can you not, enforce it? Can you not just compare the public variables to see if it is higher?

Also, what is the heap and stack? And why is the stack faster than the heap?

Another thing, I read yesterday on an online C# course that strings are structs and int's are classes? Could someone please explain why this would be diffirent? What are the reasons behind this?

And then one more question (although I cannot promise that this will be the last, I will try and finish off now). What is a constructor, and what is it used for?

Thanks, once again, for all the help. I am learning a tremendous amount from you guys.
 
Constructor:

A constructor is a special function that gets called when your class is first created, as far as im aware, structs dont have these in c#.
Example-
class MyClass
{
public:
MyClass();
};

MyClass function is the constructor for class MyClass. It is always the same name as the class name. In there you usually initialise variables that are used elsewhere in your class.

-----

Regarding enforcing public member variables vs get/set. For the public member, you would have to compare the values of high + low EVERY time you want to put a new value in, in your main code this could get very messy. If for example you have 5 places in your code where you have to set a public member, that is 5 places where you need to check high against low. However, if you did the checking in a get/set or a function, you only have 1 place in the code that does this checking. The added benefit is that if there is a mistake in that 1 section of code its easier to find rather than looking through all the 5 other sections.


Hope that makes it clear to you?

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
Ahh, ok. I understand the get/set thing now. So it is basically only to get nice structure to your code and make it more amintainable, but in effect does the same job as using variables and using functions or inline code to check for data.

That makes sence then. Thanks for the explanation.

Regarding the constructor? I presume now that it is the same scenario as the get/set thing? Allowing you to inilialise your components in a function-like structure, making your code more maintainable, in stead of scattering your initialisation code all over the place? Am I right, or am I missing it?

Now just for the heap and stack thing? Anybody knows what that is about? And do I really need to know anything about it, other than the stack being faster than the heap, and the one being reference based and the other value based?
 
Yes + Yes :).

Heap + Stack.

Heap = global memory store, when you create object dynamically they are created here.
Stack = created locally, ie a local variable in a function

Im not too sure what relavence they play in c# or managed c++ because of the garbage collection (automatic memory de-allocation when objects go out of scope). But in c/c++ its important to know about creating objects on the heap / stack.

Skute

"There are 10 types of people in this World, those that understand binary, and those that don't!"
 
Well, thanks again for all the answers. Really learned alot.
 
Ahh, ok. I understand the get/set thing now. So it is basically only to get nice structure to your code and make it more amintainable, but in effect does the same job as using variables and using functions or inline code to check for data.

Right.
Remember that in programming, Less is More.
The less code you write, the more time you have to do things other than maintain it.

So, you want fundamental business rules placed where every user of your class has no choice but to call it. So if you make the member variables private to the class (meaning outside users of the class can't access them), you then create public getters & setters, which users of your class can access. You are then able to enforce some basic rules in the setter property.

If you have a need to use that value inside your class (in some other method), you then have a choice: You can access the private member variable directly, or you can call the public setter (which will enforce the rule for your class, too).
Code:
public class Employee
{
  private decimal _SalaryHigh = 0.0m;
  private decimal _SalaryLow = 0.0m;

  public void Employee
  {
    // constructor
  }

  public decimal SalaryHigh
  {
    get
    { 
      return _SalaryHigh; 
    }
    set
    {
      if (value < SalaryLow)
      {
        throw new ArgumentOutOfRangeException("SalaryHigh");
      }
      _SalaryHigh = value;
    }
  }

  public decimal SalaryLow
  {
    get
    { 
      return _SalaryLow;
    }
    set
    {
      if (value > SalaryHigh)
      {
        throw new ArgumentOutOfRangeException("SalaryLow");
      }
      _SalaryLow = value;
    }
  }

  public void SetSalaryInfo(decimal Low, decimal High)
  {
     // using internal member variable
     // No range checking is done
     _SalaryLow = Low;
     _SalaryHigh = High;

     // Using public setter property
     // Setter will check ranges
     this.SalaryLow = Low;
     this.SalaryHigh = High;
  }
}
Which to use, and when? It depends on the behavior you want.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Thanks. It really makes sence. I always knew this (in other programming languages) and alwasy done it, just never knew that it was the same as a property get and set.

Thanks alot for clearing it all up for me. Did the courses and they just never explained it to me like this.
 
Skute said:
"...it [a struct ] cannot contain functions like a class can..."

I think you meant to say Property Accessor functions. The following code compiles perfectly. If you attempt to write a property declaration arount the two internal variables, then you get a compile-time error.

Code:
   public struct MyStruct {
      int Var1;
      int Var2;

      MyStruct(int x, int y) {
         Var1 = x;
         Var2 = y;
      }

      int GetMyVar(int which) {
         if (which == 1) {
            return Var1;
         } else {
            return Var2;
         }
      }
   }
 
One major difference between struct and class is that there is no inheritance support for Struct, it can only implement an interface. I think lack of inheritance in case of Struct is a major hold back and that could be one area where Class out performs Struct.

-Kris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top