I have a base class:
public class Base
{
public Base(X x ,Y y){
this.x = x;
this.y = y;
}
public X x{get;}
public Y y{get;}
}
and a deriver:
public class Derive : Base
{
public Derive(Z z, Q q) :Base (? ?)
{
}
private void ConstructXY(Z z, Q q)
{
//Advanced logic for creating an X and a Y
if(q.something == 5){
this.x = new X(28);
}
else{
this.x = new X(25);
}
if(this.x.something == 25 && q == 9){
this.y = new Y(1);
}
else{
this.y = new Y(5)
}
}
}
Now I can't correctly call the base constuctor without the "advanced" logic. I used to be able to call ConstructXY() from Derive.ctor() and set x and y from there, this is no longer valid since I removed the x and y setters. My real-life scenario contains a lot more logic so I am not willing to create a ternary mess.
You can call your "advanced" logic if it fits inside a static method
Here is an approach using Tuple available in C# 7 :
public class Base
{
// This constructor was added to avoid calling twice ConstructXY
public Base((X x, Y y) tuple) :
this (tuple.x, tuple.y)
{
}
public Base(X x, Y y)
{
this.x = x;
this.y = y;
}
public X x { get; }
public Y y { get; }
}
public class Derive : Base
{
public Derive(Z z, Q q) : base(ConstructXY(z, q))
{
}
private static (X x, Y y) ConstructXY(Z z, Q q)
{
X x;
Y y;
//Advanced logic for creating an X and a Y
if (q.something == 5)
{
x = new X(5);
}
else
{
x = new X(25);
}
if (x.something == 25 && q == 9)
{
y = new Y(1);
}
else
{
y = new Y(5)
}
return (x, y);
}
}
If you cannot change the access modifiers of X and Y in the base class so they are accessible for subclasses, then you will have to follow the contract, leaving the constructor the only possible place where you can set those members.
The only way to add more logic to calculate those values would be to use static methods, for example like this:
public class Derive : Base
{
public Derive(Z z, Q q)
: base(ConstructX(q), ConstructY(q, z))
{ }
private static X ConstructX(Q q)
{
if (q.something == 5)
return new X(28);
else
return new X(25);
}
private static Y ConstructY(Q q, Z z)
{
if (z.something == 25 && q.something == 9)
return new Y(1);
else
return new Y(5);
}
}
Since these are separate method calls, you cannot calculate both values “at once”, so you cannot make the result of Y depend on the result of X without redoing the calculation based on Z and Q again.
Another way you could solve this is by removing the public constructor on Derive altogether and provide a static factory method instead:
public class Derive : Base
{
private Derive(X x, Y y)
: base(x, y)
{ }
public static Derive Create(Z z, Q q)
{
// here you can use your original logic to calculate X and Y
X x = …
Y y = …
return new Derive(x, y);
}
}
Depending on your complexity of those calculations, this might be the better solution. If you do need the original Z and Q values, just extend the private constructor to also take those and store them as well:
private Derive(Z z, Q q, X x, Y y)
: base(x, y)
{
this.Z = z;
this.Q = q;
}
I don't really like this way of doing it and would avoid it if possible but you can use a ternary statement in your call to base:
public Derive(Z z, Q q)
: base(new X(xCondition ? 28 : 25), new Y(yCondition ? 1 : 5))
Use static methods to do the conversion. Like this.
public class Derive : Base
{
public Derive(Z z, Q q) :base (ConvertToX(z, q), ConvertToY(z, q))
{
}
private static X ConvertToX(Z z, Q q) {
if(q.something == 5){
return new X(28);
}
return new X(25);
}
private static Y ConvertToY(Z z, Q q) {
// TODO
}
}
Why not declare your base class setters as private:
public class Base
{
public Base(X x ,Y y){
this.x = x;
this.y = y;
}
public X x{get; private set;}
public Y y{get; private set;}
}
That way you can still set them in the constructor, and they would not be settable outside?
Related
In c#:
public class SomeClass
{
int x;
int y;
SomeClass (int x, int y)
{
this.x = x;
this.y = y;
}
}
Is there easy way to make new SomeClass without setting x and y instead to
have default values for them and if I set values to set them else to have the
default values?
Sure, with C#6 you can use auto-implemented properties:
public class SomeClass
{
public int X { get; } = 123;
public int Y { get; } = 456;
public SomeClass(){ }
public SomeClass(int x, int y)
{
this.X = x;
this.Y = y;
}
}
Of course you need a parameterless constructor.
If you instead mean default values of the type, that is done automatically(0 for numerical types).
Sure...
new SomeClass(default(int), default(int))
Or, more simply:
new SomeClass(0, 0)
The default value for int is always 0. So even if you define it with a parameterless constructor:
public SomeClass() { }
Those int class members would still default to 0.
You need to define a parameterless constructor:
public class SomeClass
{
int x;
int y;
public SomeClass {}
public SomeClass (int x, int y)
{
this.x = x;
this.y = y;
}
}
When you create an object like:
var someClass = new SomeClass();
both x and y would be initialized using their default values, which is 0.
If you don't want to do so, you could handle this by passing to the constructor that you have already declared the default values of x and y, as already David has pointed out.
Use a parameterless constructor.
Since the instances have to be created somehow using a new keyword, you can use a parameterless constructor inside your class.
public SomeClass ()
{
x = 0;
y = 0;
}
A default constructor would do that automatically.
You can use optional parameters in the constructor.
Read more on named and optional parameters.
public class SomeClass
{
// You can also write this as
// public SomeClass(int x=default(int), int y=default(int)) if you do
// not want to hardcode default parameter value.
public SomeClass(int x=0, int y=0)
{
this.X = x;
this.Y = y;
}
}
You can call it as
void Main()
{
SomeClass a = new SomeClass();
SomeClass b = new SomeClass(1);
SomeClass c = new SomeClass(2,4);
}
class experiment
{
int xCoord = 0;
int yCoord = 0;
public experiment(int x, int y) {
this.xCoord = x;
this.yCoord = y;
}
}
class result :experiment{
int zCoord = 0;
public result(int z) : base(x,y)
{
this.zCoord = z;
}
}
Can anyone help me solve this simple problem. I'm having an error base(x,y) it says the name 'x' does not exists in the current context and also goes for the y.
x and y are local fields to class experiment they are not visible in inherited class, you may call the base constructor with default values like:
public result(int z) : base(0,0)
Also please follow General Naming Conventions from Microsoft, so the class names begins with upper case character.
EDIT:
It would be better if your child class has a constructor to receive parameter x and y, and the it calls the base class constructor with those values like:
public result(int x, int y, int z) : base(x,y)
{
this.zCoord = z;
}
There is no x,y in constructor of result class.
You pass to your constructor z but tell your base constructor to recieve x and y. Though there are no x and y at that time.
Try this:
public result(int z, int x, int y) : base(x,y)
{
this.zCoord = z;
}
Or set fix values (no variables):
public result(int z) : base(0, 0)
{
this.zCoord = z;
}
I am trying to modify value in dictionary, but the compiler throws KeyNotFoundException. I'm sure, I declared that key in dictionary, because I am calling GenerateEmptyChunks() method, which fills dictionary with chunks with key of their position and values are empty for level generator. I've checked debugger and Chunks dictionary object is correctly filled with keys and values. Is it caused by my unworking CompareTo method? If yes, how I have modify CompareTo method to return right values?
public Dictionary<WPoint, WChunk> Chunks = new Dictionary<WPoint, WChunk>();
GenerateEmptyChunks() method:
public void GenerateEmptyChunks(int Xcount, int Ycount)
{
for(int x = 0; x <= Xcount; x++)
{
for (int y = 0; y <= Ycount; y++)
{
this.Chunks.Add(new WPoint(x, y), new WChunk(x, y));
}
}
}
AddBlock() method which is called by level generator for each tile:
public void AddBlock(WPoint location, int data)
{
this.Chunks[location.GetChunk()].AddTile(new WTile(location, data));
}
WChunk object:
public class WChunk
{
public int ChunkX;
public int ChunkY;
public SortedDictionary<WPoint, WTile> Tiles = new SortedDictionary<WPoint, WTile>();
public WChunk(int posX, int posY)
{
ChunkX = posX;
ChunkY = posY;
}
public void AddTile(WTile tile)
{
Tiles.Add(tile.GetLocation(), tile);
}
}
WPoint object:
public class WPoint : IComparable
{
public float X;
public float Y;
public WPoint(float x, float y)
{
X = x;
Y = y;
}
public WPoint GetChunk()
{
//Oprava pre bloky mensie ako (1,1)
if (X <= 16 && Y <= 16)
{
return new WPoint(0, 0);
}
else
{
double pX = (double)(X / 16);
double pY = (double)(Y / 16);
return new WPoint((int)Math.Floor(pX), (int)Math.Floor(pY));
}
}
public int CompareTo(object obj)
{
WPoint point2 = (WPoint)obj;
if (point2.X == this.X && point2.Y == this.Y)
{
return 0;
}
else if (point2.X >= this.X && point2.Y >= this.Y)
{
return -1;
}
else
{
return 1;
}
}
}
Any ideas why is compiler rejecting keys, when they are in dictionary?
Yes. You have not overridden GetHashCode.
Dictionary is using the GetHashCode and Equals for key comparisons, so implementing the IComparable interface is not enough. Have a look at this answer, that's exactly what you need.
I am having the following problem:
public class A {
public A(X, Y, Z) {
...
}
}
public class B : A {
public B(X, Y) : base(X, Y) {
//i want to instantiate Z here and only then pass it to the base class!
}
}
How can I solve this problem? Is there a way?
The common solution is to call a static method belonging to the type that can calculate the value of the parameter to be passed to the base constructor.
For example:
public B(int x, int y)
: base(x, y, CalculateZ(x, y))
{
}
// You can make this parameterless if it does not depend on X and Y
private static int CalculateZ(int x, int y)
{
//Calculate it here.
int exampleZ = x + y;
return exampleZ;
}
Do note that CalculateZ cannot be an instance method, because the this reference is not available in constructor initializers.
From the language-specification 10.11.1 Constructor initializers:
An instance constructor initializer
cannot access the instance being
created. Therefore it is a
compile-time error to reference this
in an argument expression of the
constructor initializer, as is it a
compile-time error for an argument
expression to reference any instance
member through a simple-name.
EDIT: Changed 'instance' to 'static' in the description.
You need to calculate Z before the constructor itself gets called. If it's simple you can use an inline expression, else you'll need to define a helper function.
Using a helperfunction:
public class A {
public A(X x, Y y, Z z) {
...
}
}
public class B : A {
private static Z calculateZ()
{
}
public B(X x, Y y) : base(X, Y, calculateZ()) {
}
}
Without helperfunction:
public B(X, Y) : base(X, Y, X+Y) {
}
public abstract class A {
public A(X, Y) {
...
}
public abstract Z TheVariableZ{get;set;}
}
public class B : A {
public B(X, Y) : base(X, Y) {
//i can only calculate Z here!
}
public override Z TheVariableZ{//implement it here}
}
And if you can't make A abstract, just mark the property as virtual
Possibly this:
public abstract class A {
public A(X, Y) {
CalculateZ();
}
abstract void CalculateZ();
}
public class B : A {
public B(X, Y) : base(X, Y) {
}
override void CalculateZ()
{
... Calculate here.
}
}
Was a bit shocked to discover that System.Drawing.PointF appears to have operators for subtracting sizes but not other PointFs. So I'm trying to write my own PointF class, but it needs to be able to have System.Drawing.Points automatically converted to it, or it really doesn't add any convenience. So I wrote these constructors:
public PointF(float x = 0, float y = 0)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
But I'm still getting this error:
cannot convert from 'System.Drawing.Point' to 'my_namespace.PointF'
(I have a function that accepts a my_namespace.PointF but I'm passing in a System.Drawing.Point).
Shouldn't the 3rd constructor kick in and auto-convert it?
Do you have an implicit conversion defined in your my_namespace.PointF class? It won't automatically convert otherwise.
public PointF(float x = 0, float y = 0)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
//add this:
public static implicit operator PointF(System.Drawing.Point pt)
{ return new PointF(pt); }
Have you considered the option of writing an 'extension method' instead of rolling out your own class ?
You can't have operator overloading per se via extn. methods (proposed in next revision of the framework).. but you should be able to use a synonymous method called Add() for + and get by.
This compiles for me:
class PointF {
float x; float y;
public PointF(float x, float y)
{
this.x = x;
this.y = y;
}
public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }
public static implicit operator PointF(System.Drawing.Point pt) { return new PointF(pt); }
public static implicit operator PointF(System.Drawing.PointF pt) { return new PointF(pt); }
}
//....
static void test(pointf.PointF p) {
}
//....
test(new System.Drawing.PointF(1, 1));