C# Base Constructor Inheritance - c#

I'm trying to inherit from a base class but I'm getting an error that I can't figure out. This is the base class:
class Item
{
protected string name;
public Item(string name)
{
this.name = name;
}
}
And this is the inherited class:
class ItemToBuy : Item
{
private int lowPrice;
private int highPrice;
private int maxQuantity;
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
}
The issue is this line:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
where 'name' is underlined with the error message "An object reference is required for the non-static field, method or property 'Item.name'. If I replace it with a string literal the error message isn't there. What am I doing wrong with inheriting the constructor?

your ItemToBuy class does not have any knowledge of "name".
The way you build the constructor, "name" needs to be a defined string.
Let's say that your constructor looks like this:
class ItemToBuy : Item
{
private int lowPrice;
private int highPrice;
private int maxQuantity;
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
}
this will work because the name parameter is defined.
So, you either do it like that or pass a hardcoded value like you did to make it work.

You need to have the name in the ctor of the ItemToBuy class too
public ItemToBuy(string name ,int lowPrice, int highPrice, int maxQuantity) : base(name)

public ItemToBuy(int lowPrice, int highPrice, int maxQuantity) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
should be changed to:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity, string name) : base(name)
{
this.lowPrice = lowPrice;
this.highPrice = highPrice;
this.maxQuantity = maxQuantity;
}
You need to specify the name parameter in the constructor, as per my code above.

you need to receive the name in the constructor of ItemToBuy:
public ItemToBuy(int lowPrice, int highPrice, int maxQuantity,string name) : base(name)

Related

C#, write a constructor of a class from an abstract base class "Parcelable", which is from the Android Library

In C#, I need to write a constructor of a class as below which extends base class from android Library i.e. "Parcelable". I am getting an Error "Parcelable" does not contain a constructor that takes 0 arguments.
I saw C# Error: Parent does not contain a constructor that takes 0 arguments and Parent does not contain a constructor that takes 0 arguments but it did not work.
My Class is as follows :
...
using Parcel = Android.OS.Parcel;
using Parcelable = Android.OS.Parcelable;
/// <summary>
/// Created by hashmi on 07/07/2015.
/// </summary>
public class Classname: Parcelable
{
private int id;
private string name;
private string address;
private string latitude;
private string longitude;
public Classname(int id, string name, string address, string latitude, string longitude)
{
this.id = id;
this.name = name;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
}
...
}
Code for the base class Parcelable is as follows:
using System;
using Android.Runtime;
using Java.Lang;
namespace Android.OS
{
[Register("android/os/Parcelable", ApiSince = 1, DoNotGenerateAcw = true)]
public abstract class Parcelable : Java.Lang.Object
{
[Register("CONTENTS_FILE_DESCRIPTOR")]
public const int ContentsFileDescriptor = 1;
[Obsolete("This constant will be removed in the future version. Use Android.OS.ParcelableWriteFlags enum directly instead of this field.")]
[Register("PARCELABLE_WRITE_RETURN_VALUE")]
public const ParcelableWriteFlags ParcelableWriteReturnValue = ParcelableWriteFlags.ReturnValue;
}
}
The base class is an Android Library abstract Class.
I want to write a Constructor like "Classname" above without modifying the abstract base class that is "Parcelable".
I have edited the original code with the following code.
using Parcel = Android.OS.Parcel;
using Parcelable = Android.OS.Parcelable;
/// <summary>
/// Created by hashmi on 07/07/2015.
/// </summary>
public class LocationDetail : Parcelable
{
private int id;
private string name;
private string address;
private string latitude;
private string longitude;
public LocationDetail(int id, string name, string address, string latitude, string longitude)
: base(id, name, address, latitude, longitude)
{
this.id = id;
this.name = name;
this.address = address;
this.latitude = latitude;
this.longitude = longitude;
}
...
}
The new error is "Parcelable" does not contain a constructor that takes 5 arguments
From the looks of the Android documentation for Parcelable, it doesn't appear to implement any constructors, it implements a creator interface to build the Parcelable from a Parcel.
This is a typical implementation of Parcelable according to the android docs (In Java):
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
As you can see Parcelable itself contains no constructors. This SO thread talks a little about the concept of Parcelables in Android.
I've come across a couple of guides that outline how to use this in Xamarin, one suggests that you can implement it like this: (This guide can be found here)
public class UserParcelable : Java.Lang.Object, IParcelable
{
public UserParcelable()
{
}
public int DescribeContents()
{
throw new NotImplementedException();
}
public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags)
{
throw new NotImplementedException();
}
}

Iteration through properties with custom attributes in a class

I've got a class like this with some custom attributes. I'm not sure whether i actually have to implement these.
[AttributeUsage(AttributeTargets.Field)]
private class IsValue : Attribute { }
[AttributeUsage(AttributeTargets.Field)]
private class IsRep : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
private class IsConstant : Attribute { }
public static class Constants
{
[IsConstant]
public static class EulerGamma
{
[IsValue]
public const double Value = 0.5772156649015;
[IsRep]
public const string Str = "γ";
}
[IsConstant]
public static class EulerNumber
{
[IsValue]
public const double Value = 2.718281828459;
[IsRep]
public const string Str = "e";
}
[IsConstant]
public static class Pi
{
[IsValue]
public const double Value = 3.1415926535898;
[IsRep]
public const string Str = "π";
}
[IsConstant]
public static class GoldenRatio
{
[IsValue]
public const double Value = 1.6180339887499;
[IsRep]
public const string Str = "φ";
}
}
Let's say this is in some class "MyMathClass", where I'd like to implement a method like this:
string ValueOrString(double x)
This method would return string representation of the constant if the number passed is equal to the constant, else it would return the original number.
So, if i passed exactly 3.1415926535898 this method would give me the string "π".
If is passed for example 2.5315621321 this would return me "2.5315621321" (string).
Would you please help me out?
I would create a class that uses a dictionary:
public static class Constants
{
static Dictionary<double, string> constantNames;
static Constants()
{
Constants.constantNames = new Dictionary<double, string>();
Constants.constantNames.Add(3.1415926535898, "π");
Constants.constantNames.Add(2.718281828459, "e");
}
public static string ValueOrString(double value)
{
if (constantNames.ContainsKey(value))
{
return constantNames[value];
}
else
{
return value.ToString();
}
}
}
When the function string ValueOrString(double value) is called, you can check if the provided value exists in the dictionary. If it exists, you retrieve the name of the constant from it. Otherwise, you return the value as a string.

Basic inheritance - too verbose?

I'm looking for a programmatically smarter way to inherit here. I'm very new to the world of programming so it's more of methodology I'm looking for here. Is this the right way to inherit?
The base class in this case has a large constructor. Having to call base(w, x, y, z) in each inherited class looks incredibly verbose. Quite frankly, it looks like lazy or bad code.
public class DataStudioGear : DataItem {
string name;
int moneyValue;
int compression;
int wideness;
int wowFactor;
public DataStudioGear(string name, int value, int comp, int wide, int wow) {
this.name = name;
moneyValue = value;
compression = comp;
wideness = wide;
wowFactor = wow;
}
}
So now any class that inherits from this has to of course, pass those variables along to the constructor. That leaves me with a bunch of classes that look like this:
public class Console : DataStudioGear {
public Console(string name, int value, int comp, int wide, int wow) : base(name, value, comp, wide, wow) {
}
}
public class Compressor : DataStudioGear {
public Compressor(string name, int value, int comp, int wide, int wow) : base(name, value, comp, wide, wow) {
}
}
These constructors are huge. Although I'm very new to programming in general, it just looks like bad code.
Is there a better solution for what I'm trying to accomplish here?
Consider using the factory pattern. The below code uses a static generic method in the base class to generate a subclass while populating the property values.
public class DataStudioGear : DataItem
{
string _name;
private int _moneyValue;
int _compression;
int _wideness;
int _wowFactor;
public static T DataTestFactory<T>(string name, int value, int comp, int wide, int wow)
where T : DataStudioGear, new()
{
return new T { _name = name, _moneyValue = value, _compression = comp, _wideness = wide, _wowFactor = wow};
}
}
public class Console : DataStudioGear { }
public class Compressor : DataStudioGear { }
[TestMethod]
public void TestDataItemFactory()
{
Console console = DataStudioGear.DataTestFactory<Console>("test", 1, 1, 1, 1);
Compressor compressor = DataStudioGear.DataTestFactory<Compressor>("test", 1, 1, 1, 1);
}

how to get parameter in other class

This is my first class:
public class IntelliChart
{
string _chartName;
public IntelliChart(string chartName)
{
_chartName = chartName;
_chartParamProvider = new ChartParameterProvider();
_userBLL = new UserBLL();
_factormasterBll = new HealthFactorMasterBLL();
}
}
Below is my second class:
internal class DefaultAllReadingsDataProvider : DataProvider
{
internal override OutputData GetOutputData(Guid userId, int N, int pageNum)
{
}
}
Now in the above code i want to get _chartName in second class. i try session, viewstate and also create global variable but its not working.
Please try in that way:-
In first class:-
public string _chartName;
In Second Class:-
internal class DefaultAllReadingsDataProvider : DataProvider
{
internal override OutputData GetOutputData(Guid userId, int N, int pageNum)
{
IntelliChart iclass = new IntelliChart("test");
Response.Write(iclass._chartName);
}
}

Compile Error with Class Inheritance

I am getting a compile error in my PC class on the line where I am setting it's inherited STR stat. The compiler error getting is an "Entity.Stat does not contain a constructor that takes 2 arguments. Now I know this not to be the case, because the base Entity class makes the same declarations in its initialization sequence.
If anyone can take a look to see what I'm doing wrong, that would be great. The StatType item is an ENUM that is declared in another file, and is working without issues.
class PC : Entity {
private Class job;
public PC(string name, Race race, Class job, int STR, int DEX, int CON, int WIS, int INT, int CHA){
this.name = name;
this.race = race;
this.job = job;
// This line here is the line giving me difficulties.
this.STR = new Entity.Stat(STR, StatType.Strength);
}
}
public class Entity
{
protected string name;
protected Race race;
protected Stat STR;
protected Stat DEX;
protected Stat CON;
protected Stat WIS;
protected Stat INT;
protected Stat CHA;
public Entity(){ }
public Entity(string name, Race race, int STR, int DEX, int CON, int WIS, int INT, int CHA){
this.name = name;
this.race = race;
this.STR = new Stat(STR, StatType.Strength);
this.DEX = new Stat(DEX, StatType.Dexterity);
this.CON = new Stat(CON, StatType.Constitution);
this.WIS = new Stat(WIS, StatType.Wisdom);
this.INT = new Stat(INT, StatType.Intelligence);
this.CHA = new Stat(CHA, StatType.Charisma);
}
private struct Stat
{
private int id;
private int value;
private int modifier;
public Stat(int value, StatType id)
{
this.id = (int)id;
this.value = value;
this.modifier = ((value - 10) / 2);
}
public int Value
{
get
{
return this.value;
}
set
{
this.value = value;
this.modifier = ((value - 10) / 2);
}
}
public readonly int Modifier
{
get { return this.modifier; }
}
}
}
Your Stat struct is private, meaning it's only visible to the Entity class, not subclasses. Make it protected and it will be visible to the Entity class and any subclasses.
You can't have readonly properties, either, so you're going to get a compiler error on the line public readonly int Modifier as well.
I believe you need to switch Stat to protected:
protected struct Stat
I don't think that the PC class can see the Stat class because it's not visible to it - only to Entity.

Categories