What are these things doing in C#?

I’m switching to C# from unityscript and so far I’m enjoying the ride :slight_smile:

Can someone that knows c# well explain what these things are doing?

1: something = (float)sometingg; Why is “(type)” there?
2: In some functions, there’s “get” and “set”, what exactly does it do?

float something{
    get{
    
    }
    set{

    }
}

Edit: I misread the first question. See below for updated and correct answers

1: That is called casting, it is used to convert between two datatypes. (Not all datatypes can be converted automatically via casting) You would use this for example to convert between a float and an int.

void Start()
{
    float foo = 2.4f;
    int bar = 1;
    Debug.Log(Add(x, (float)y));
}

float Add(float x, float y)
{
   return x + y;
}

Another thing to watch out for is when doing calculations between integers that can result in a float value (dividing for example), you will need to cast one of the integers to a float otherwise it is taken as simply integer math, so the floating point part is simply dropped.

int x = 10;
int y = 3;

float answer = x/y; // answer = 3  : incorrect if expecting floating point
answer = x/(float)y; // answer = 3.333333  : correct if expecting floating point.

2: these are called properties, they are generally used to expose private variables. They can be used to perform validation on changes to variables. So if you wish to only be able to set a variable to a value between 1 and 100, it is possible to use properties to do that.

The get{} defines what gets returned when calling

float something = theClass.something;

The set{} defines what happens when a value is assigned to the something property.

float something = 10.0f;
theClass.something = something;
  1. that is a type cast, meaning that sometingg will be forced to be of type float. Read Type conversion - Wikipedia .

  2. this is C# shorthand for getters and setters. Instead of creating methods like
    public string GetName(){ return name;} public void SetName(string newName){ name = newName;} You type
    public string Name{ get { return name;} set{ name = value;} }

Read more from http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx .

The types in parentheses are called “casts”. Basically, it converts one datatype to another. Say I had an integer called “foo”, and I had a function that only accepts floats as parameters. I would need to convert “foo” to a float in order to use it as a parameter. For example:

void main(){

int foo = 1;
float sqrtOfFoo = SquareRoot((float)foo);

//Since SquareRoot() requires a float as input, we need to "cast", or convert, foo as a float.

}

float SquareRoot(float input){
return Mathf.Sqrt(input);
}