Need help understanding a few c# concepts
From my reading, abstract classes are not instantiated. But I also read somewhere else that they do in fact instantiate as an object. I am not sure which is correct.
What is the 'this' keyword doing in this scenario? And why is the 'this' keyword only used on 'position'? If the author used it on 'position' why would he not apply it to 'id' & 'type'?
All help is appreciated.
using UnityEngine;
public abstract class Entity : MonoBehaviour, IEntity
{
public int id { get; set; }
public EntityType type { get; set; }
public Vector3 position
{
get { return this.transform.position; }
set { this.transform.position = value; }
}
}
public enum EntityType
{
Player,
Enemy
}
using UnityEngine;
public interface IEntity
{
int id { get; set; }
EntityType type { get; set; }
Vector3 position { get; set; }
GameObject gameObject { get; }
}
C# is a real program$$anonymous$$g language and Unity uses it pretty much exactly as anyone else does. This means you can find many detailed explanations of anything in non-Unity forums. Very, very easy to search using "C# blah-blah."
Answer by troien · Apr 23, 2016 at 04:11 PM
this is just to indicate that you want this class his variable/property/method etc. It is only required when you have 2 variables with the same name (in a different scope) and in all other cases it is optional and one could argue it adds clarity.
When inherriting, and overwriting, the base keyword can be used to distinguish this from the base where you inherrit from
public class Example : MonoBehaviour
{
private int test;
public void ExampleMethod(int test)
{
this.test = test; // set our private variable to our parameter
test = test; // Set value of our parameter to value of our parameter. Your compiler will complain on this one
}
}
Abstact classes can't be instantiated themself. But they can be inherrited, and those inherrited classes can be instantiated (as long as they aren't abstract ofcourse).
But really, the links to the MSDN sections provide a much more in depth explanation about the subjects...
Thank you very much for the explanation and example. I understand now!