I need to create an inherritance of an Event as a SwimmingEvent however I'm receiving an error that the constructor doens't contain 0 arguments, the problem is I don't know which arguments are meant to be passed through. Any help would be greatly appreciated.
//Base Class
class Event
{
private string m_evName;
private string m_evDate;
private string m_evTime;
private string m_evFee;
private string m_evVenue;
private List<Athlete> m_athletes;
public String EvName { get { return m_evName; } }
public String EvDate { get { return m_evDate; } }
public String EvTime { get { return m_evTime; } }
public String EvFee { get { return m_evFee; } }
public String Venue { get { return m_evVenue; } }
//Getters/Setters - Making private variables avilable in public space through class method
public Event(String EvName, String EvDate, String EvTime, String EvFee, String EvVenue)
{
m_evName = EvName;
m_evDate = EvDate;
m_evTime = EvTime;
m_evFee = EvFee;
m_evVenue = EvVenue;
m_athletes = new List<Athlete>();
}
}
//child class
class SwimmingEvent : Event
{
private String m_distance;
private String m_inOutVar;
public SwimmingEvent(String Distance, String InOrOut)
{
m_distance = Distance;
m_inOutVar = InOrOut;
}
}
Since SwimmingEvent is an Event, you need to pass all arguments that you pass to the Event's constructor to the constructor of SwimmingEvent, and then some:
public SwimmingEvent(String EvName, String EvDate, String EvTime, String EvFee, String EvVenue, String Distance, String InOrOut)
: base (EvName, EvTime, EvFee, EvVenue, Distance) {
m_distance = Distance;
m_inOutVar = InOrOut;
}
using System;
public class MyBase
{
int num;
public MyBase(int i )
{
num = i;
Console.WriteLine("in MyBase(int i)");
}
public int GetNum()
{
return num;
}
}
public class MyDerived: MyBase
{
// This constructor will call MyBase.MyBase(int i)
***//You are missing this.***
public MyDerived(int i) : base(i)
{
}
}
You need to pass all arguments back to your parent.
class SwimmingEvent : Event
{
private String m_distance;
private String m_inOutVar;
public SwimmingEvent(String Distance, String InOrOut, string evName) : base (evName,"b","c", "d", "e")
{
m_distance = Distance;
m_inOutVar = InOrOut;
}
}
May be something like this:
public class Event
{
public Event() {} // public empty ctor
....
....
}
and derived
public class SwimmingEvent : Event
{
}
In this way you will avoid (assuming that is what you want) the compile time error, as a ctor with empty arguments list is already present in base class.
If this is not what you're searching for, please clarify.
in C#, before constructor of derived class (such as SwimmingEvent constructor) is called, constructor of base class (Event class) must be called too. Arguments of call to base class's constructor are usually specified using "base" keyword like this:
class SwimmingEvent : Event
{
....
public SwimmingEvent(String Distance, String InOrOut)
:base(/*Arguments for base class constructor*/)
{
//Constructor of derived class
}
}
if you omit ":base(...)", compiler assumes calling parameterless constructor of base class, such as if you write ":base()". But there is no parameterless constructor in base class, so you get the error.
You must either create parameterless constructor in Event class, or add "base" keyword and specify arguments for calling existing Event class's constructor in SwimmingEvent's declaration.
Related
I wrote C# code as described below that inherits a class from a generic class with static methods. I want to call the child class for its static methods (inherited from the base class) without having to specify the type.
EDITED! More "real" code
public class Rec
{
public string Name { get; set; }
public override string ToString() { return this.Name; }
public virtual void Load() { /* HERE IT READS A TEXT FILE AND LOAD THE NAME */ }
}
public class BaseClass<T> : Rec
{
public T Argument { get; set; }
public override void Load() { /* NOW IT LOADS ALSO THE ARGUMENT */ }
public static H Method<H>() where H : Rec, new()
{
H iH = new H();
iH.Load();
iH.Name += " " + iH.Argument.ToString();
return iH;
}
}
public class Child : BaseClass<string> { }
public class SomeOtherClass
{
public void Test()
{
Child i = Child.Method();
//instead of Child.Method<Child>();
}
}
So, instead of having to call method<h>() i'd like to just call method(), so the code should assume that "h" is the caller type. Like in:
How can I do it?
Static methods are not inherited in C#
See this answer for an idea of a potential implementation: Stack Overflow whats-the-correct-alternative-to-static-method-inheritance
You could change method<h> to method and make it an instance method:
public class BaseClass<T> where T, new()
{
public T method() { /* RETURN SOMETHING */ }
}
And then call it as follows:
public class ABC : Child
{
public void Test()
{
var iABC = this.method();
}
}
I need the separate classes for Xml Serialization. I'd like to know if there is a simpler way for the inheriting BuildingDetail class to acquire the property values from the parent Building class.
Parent Class
public class Building
{
public int BuildingId;
public string BuildingName;
protected Building()
{
}
private Building(int buildingId, string buildingName)
{
BuildingId = buildingId;
BuildingName = buildingName;
}
public static Building Load(int buildingId)
{
var dr = //DataRow from Database
var building = new Building(
(int) dr["BuildingId"],
(string) dr["BuildingName"]);
return building;
}
}
Inheriting Class
public class BuildingDetail : Building
{
public BaseList<Room> RoomList
{
get { return Room.LoadList(BuildingId); }
}
protected BuildingDetail()
{
}
// Is there a cleaner way to do this?
private BuildingDetail(int buildingId, string buildingName)
{
BuildingId = buildingId;
BuildingName = buildingName;
}
public new static BuildingDetail Load(int buildingId)
{
var building = Building.Load(buildingId);
var buildingDetail = new BuildingDetail(
building.BuildingId,
building.BuildingName
);
return buildingDetail;
}
}
Thanks.
Firstly, change your base class constructor access modifier to protected. And then you can call base class constructor with base keyword:
private BuildingDetail(int buildingId, string buildingName)
: base(buildingId, buildingName)
{
...
}
It will call the base constructor first. Also if you don't put the :base(param1, param2) after your constructor, the base's empty constructor will be called.
I have the following base class:
public class Baseclass
{
public Baseclass(string anyparam)
{
}
}
I want to execute a lambda inside of the constructor of the child class:
public class Subclass : Baseclass
{
public Subclass() : base(delegate()
{
string returnstring;
// Do Something
return returnstring;
})
{
}
}
I don't want to waste any method on this, and I've not seen any example solving this without declaring the parameter type as func. How do I do this in C#?
You don't have to declare parameter as Func, you can create Func instance inline and call it:
public class Subclass : Baseclass
{
public Subclass()
: base((new Func<string>(() =>
{
const string returnstring = "a";
// Do Something
return returnstring;
})()))
{
}
}
It it looks very ugly, can produce problems and I don't recommend it to you.
I think the best you can do here is overload your base class constructor:
public class Baseclass
{
public Baseclass(string anyparam)
{
}
public Baseclass(Func<string> f):this(f())
{
}
}
public class Subclass : Baseclass
{
public Subclass()
: base(()=>
{
string returnstring="foo";
// Do Something
return returnstring;
})
{
}
}
I have a class that requests that when called a string is sent when requesting / initializing it.
class Checks
{
public Checks(string hostname2)
{
// logic here when class loads
}
public void Testing()
{
MessageBox.Show(hostname2);
}
}
How would it be possible to take the string "hostname2") in the class constructor and allow this string to be called anywhere in the "Checks" class?
E.g. I call Checks(hostname2) from the Form1 class, now when the Checks class is initialized I can then use the hostname2 string in my Checks class as well
Declare a member inside the class and assign the value you passed to the member inside the constructor:
class Checks
{
private string hostname2;
public Checks(string hostname2)
{
this.hostname2 = hostname2; // assign to member
}
public void Testing()
{
MessageBox.Show(hostname2);
}
}
If you also need to have outside access, make it a property:
class Checks
{
public string Hostname2 { get; set; }
public Checks(string hostname2)
{
this.Hostname2 = hostname2; // assign to property
}
public void Testing()
{
MessageBox.Show(Hostname2);
}
}
Properties start with a capital letter by convention. Now you can access it like this:
Checks c = new Checks("hello");
string h = c.Hostname2; // h = "hello"
Thanks to Andy for pointing this out: if you want the property to be read-only, make the setter private:
public string Hostname2 { get; private set; }
You need to copy the constructor argument in a class variable:
class Checks {
// this string, declared in the class body but outside
// methods, is a class variable, and can be accessed by
// any class method.
string _hostname2;
public Checks(string hostname2) {
_hostname2 = hostname2;
}
public void Testing() {
MessageBox.Show(_hostname2);
}
}
You can expose a public property to retun the hostname2 value which is the standard for exposing your private varibles
class Checks
{
private string _hostname;
public Checks(string hostname2)
{
_hostname = hostname2;
}
public string Hostname
{
get { return _hostname; }
}
}
I got an abstract base class
public class Base
{
public abstract String Info { get; }
}
and some children.
public class A : Base
{
public override String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String Info { get { return "B does ..."; } }
}
This is mere a constant but I want to make sure using Base that all classes implement it.
Now I sometimes do not have an object instance but want to access A.Info - this is not possible due it is a instance property.
Is there another way than implementing the same property on instance AND on static level? That would be feel like a duplicate violating DRY programming style.
NEW EDIT: I now see this two solutions:
public class Base
{
public abstract String ClassInfo { get; }
}
public class A : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "A does ..."; } }
}
public class B : Base
{
public override String ClassInfo { get { return Info; } }
public static String Info { get { return "In B we do ..."; } }
}
With this I can do with any object of type Base something like object.ClassInfo but also use the value in my factory hardcoded like if(A.Info) return new A(). But I have to implement two properties for the same information in every class.
On the other hand:
public class Base
{
public abstract String ClassInfo { get; }
public static String GetClassInfo<T>() where T : BaseControl, new()
{
T obj = new T();
return obj.ClassInfo;
}
}
public class A : Base
{
public override String ClassInfo { get { return "text A"; } }
}
public class B : Base
{
public override String ClassInfo { get { return "text B"; } }
}
Due to the abstract Base it is made sure that ClassInfo is always implemented. Calls with obj.ClassInfo and Base.GetClassInfo<A>() are okay. But with this every child of Base must have a default constructor without arguments and we loose performance with the unneccessary created instance.
Is there any other idea? Which one would you prefer and why?
If you need specific return results of your static properties, you're better of either
a) Instance properties
2) Attributes
In the example you've already given, you've got an instance of Base, which means you can just make the instance property virtual:
public class Base
{
public virtual string Info { get { return "From Base"; } }
}
public class A : Base
{
public override string Info { get { return "From A"; } }
}
If you wanted to go the attribute route, you define it as such:
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class InfoAttribute : Attribute
{
public InfoAttribute(string info) { this.Info = info; }
public string Info { get; private set; }
}
[InfoAttribute(Info = "From Base")]
public class Base
{
public string GetInfo()
{
var attr = GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
}
[InfoAttribute(Info = "From A")]
public class A : Base { }
If you wanted to call it as a static function call, you could make this change:
public static string GetInfo(Base instance)
{
var attr = instance.GetType()
.GetCustomAttributes(typeof(InfoAttribute), true)
.FirstOrDefault();
return (attr == null) ? null : attr.Info;
}
And then call it as: Base.GetInfo(instance);. All in all, not very elegant!
This is not possible.
static members cannot be virtual or abstract.
You should make an abstract instance property.
Statics can't be overridden. If you truly want to do something like that, you'd want an instance property that is virtual in the base that gets overridden in the subclasses.
Does it compiled? I don't think so. Static cannot be marked as override, virtual or abstract.