I’m trying to understand base constructor implementation. Consider this situation
If I have base class Sport
public class Sport
{
public int Id { get; set; }
public string Name { get; set; }
public Sport()
{
Console.WriteLine("Sport object is just created");
}
public Sport(int id, string name)
{
Console.WriteLine("Sport object with two params created");
}
}
Now I have basketball class which inherhit Sport class and I want to on basketball object initialization to use second constructor with two params.
public class Basketball : Sport
{
public Basketball : base ( ???? )
{
?????
}
}
First I was thinking to use private fields int _Id and string _Name and to use them in the constructor call
public Basketball : base ( int _Id, string _Name )
{
Id = _Id;
Name = _Name;
}
But that doesn’t make sense of using inheritance, so please explain me on this example.
Updated
Thanks everyone, I’m using code like this and it’s ok.
public Basketball(int id, string name) : base (id, name)
{
Id = id;
Name = name;
}
Just to make sure, On this line public Basketball(int id, string name) : base (id, name) I’m declaring variables id, name, since my original are Capitalized vars, and using as params on base (id, name) to hit my base contructor.
Thank everyone., very helpful/
You have to pass
valuesorvariablesof thederives classto thebase class constructorif the base class constructor does not have anydefault parameterless constructor.You dont need to declare anything in the base constructor call
The main purpose of base keyword is to call the
base class constructor.In general,if you do not declare any constructor of your own,the compiler creates a
default constructorfor you.But if you define your own constructor having
parameter,then the compiler does not create thedefault parameterless constructor.So in the case where you dont have a default constructor declared in the base class and want to call a base class constructor having parameters,you have to call that base class constructor and pass the required values through
basekeywordDo it like this
OR
OR
OR
is similar to
It all depends on how you want your class to behave when the
derivedclass is instantiated