Modifying variable from a derived class [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've looked around but couldn't find a concrete answer to my question.
This is a part of my abstract class Account I am interested in :
public abstract class Account
{
private decimal balance;
public decimal Balance
{
get
{
return this.balance;
}
protected set
{
if (value < 0)
{
throw new ArgumentException("Balance can't be negative");
}
balance = value;
}
}
protected Account(decimal balance)
{
this.Balance = balance;
}
}
Now I have a derived class called DepositAccount which works direclty with the Balance property,using a Withdraw() method from my IWithdraw interface.
public class DepositAccount : Account, IWithdraw
{
public DepositAccount(decimal balance)
: base(balance)
{
}
public void Withdraw(decimal amount)
{
if (amount > this.Balance)
{
throw new ArgumentException("Not enough balance!");
}
this.Balance -= Balance;
}
}
My question is how to best implement the Balance property in the base Account class?
I only want derived classes(those accounts that will be able to withdraw or deposit money) to be able to modify it(thus the protected set).
Shall I set the property to protected rather than public or keep only the setter protected?

Properties are syntactic sugar to make accessors easier and elegant to implement, but they still compile into regular methods.
How you would solve your issue if you would be talking about methods instead of properties? I guess you would end with the same solution: what modifies Balance would be protected and retrieving its value would be public.
If you want to publicly access Balance, leave it public, otherwise use protected.

Related

Why would an empty class serve as the base class for several generic classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm looking over some scripts from a Unity project called 2D GameKit, & I'm trying to learn from piecing together the purpose of each. In one of them that serves as a mechanism for persistent storage, I noticed that several generic classes were derived from an empty base class. Why?
Here is a sample of the code:
public class Data
{
}
public class Data<T> : Data
{
public T value;
public Data(T value)
{
this.value = value;
}
}
public class Data<T0, T1> : Data
{
public T0 value0;
public T1 value1;
public Data(T0 value0, T1 value1)
{
this.value0 = value0;
this.value1 = value1;
}
}
So that you can check (know / compare) that a certain object is definitely data. If you don't have a base class, when you want to check if an object is certainly a type of data before processing it, you will need to compare with Data<T> AND Data<T0, T1> and also any other data types that is created in the future

Java style polymorphism in C#? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to use Java style polymorphism in C#. Is it possible?
Here is an example that does not compile
using System;
namespace HelloWorld
{
public class Program
{
public static void Main (string[] args)
{
Triangle triangle = new Triangle(2);
Square square = new Square(3);
printID(square);
}
public void printID(Shape s){
Console.WriteLine ("id is " + s.id);
}
}
public class Shape{
public int id;
}
public class Triangle: Shape{
float b;
float height;
float area(){
return b*height/2;
}
public Triangle(int k){
id=k;
}
}
public class Square: Shape{
float side;
float area(){
return side*side;
}
public Square(int k){
id=k;
}
}
}
The message is
MyClass.cs(11,4): error CS0120: An object reference is required to access non-static member `HelloWorld.Program.printID(HelloWorld.Shape)'
Thanks!
Error is not related to polymorphism - you are calling non-static method from static method Main. You should make printID static as well.
public static void printID(Shape s){
Console.WriteLine("id is " + s.id);
}
Also I suggest you to:
Stick with C# naming guidelines when you are writing C# code. Methods and properties should have PascalCase names.
Use properties instead of public fields
If any shape should have and id, consider to create public Shape(int id) constructor in base class and call that constructor from derived classes via : base(id)
Improve naming - if you are passing id, then call variable id instead of k.

How to prevent class instantiation with dependency injection? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I had an interview question that asked roughly the following: with dependency injection, how do you prevent all of the classes from being instantiated? What if you only want a few, but not all? There are good reasons, they said, for example to avoid them all being in memory at the same time...
I've tried to research this question but it's hard to even figure out the best search term is. And no answers could I find.
A simple way would be to create it with a constructor and instantiate a single class based on a flag or switch. Here is a simple example that shows that only a single OtherClass or OtherClass2 would be instantiated.
I would like to add however that it isn't really Dependency Injection that allows the prevention of instantiation. You could get rid of the DI and have tightly coupled classes and still have a single instance of a class. So maybe I am not understanding the question correctly or maybe the interviewer asked it in a different context/manner?
class AppStart
{
OneClass One;
int _whatToCreate = 0;
public int WhatToCreate
{
get { return _whatToCreate; }
set { _whatToCreate = value; }
}
public void Start()
{
if (_whatToCreate > 0)
{
One = new OneClass(new OtherClass());
}
else
{
One = new OneClass(new OtherClass2());
}
One.PerformSomething();
}
}
class OneClass
{
IDoSomething _doSomething;
public OneClass(IDoSomething doSomething)
{
_doSomething = doSomething;
}
public void PerformSomething()
{
_doSomething.DoSomething();
}
}
class OtherClass : IDoSomething
{
public void DoSomething()
{
//throw new NotImplementedException();
}
}
class OtherClass2 : IDoSomething
{
public void DoSomething()
{
//throw new NotImplementedException();
}
}
interface IDoSomething
{
void DoSomething();
}

What is the difference between these two c# abstract classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
So I was following a c# tutorial the otherday (still a begginer) and I saw how the class ATMState was defined:
public abstract class ATMState
{
private ATM atm;
public ATM Atm
{
get { return atm; }
set { atm = value; }
}
private int dummyCashPresent = 1000;
public int DummyCashPresent
{
get { return dummyCashPresent; }
set { dummyCashPresent = value; }
}
public abstract string GetNextScreen();
}
To be honest, I find those declaraions rather confusing, so I decided to redo it in my own way:
public abstract class ATMState
{
public ATM Atm { get; set; }
public int DummyCashPresent { get; set; }
public ATMState()
{
DummyCashPresent = 1000;
}
public abstract string GetNextScreen();
}
What is the difference? Which one is better and why?
What is the difference?
You're using "automatic properties", the sample code is not. Perhaps the sample was written before automatic properties were introduced to C#.
Which one is better and why?
Generally automatic properties are better: more compact code is less to read and understanding. If you have no logic to put in the getter or setter you should be using automatic properties.
However, currently1 you cannot set a breakpoint on either the getter or setter of an automatic property, thus to be able to track accesses one sometimes need to break out with an explicit backing field.
1 I believe this will change in VS2015.

How can i create dynamic variables on the fly in c# using Reflection? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm creating a simulator of ecosystems where species can be used to simulate various diseases, my problem is that I start using 4 species but if I need more ... I need more variables to store, my question is, Is there any way through Reflection to let me create dynamic variables during the execution of an event in my program? Thank you! i'm using Windows Presentation Foundation and C#
The normal way to handle this is to have a base class for your disease species and then use a collection to hold them all:
public abstract class DiseaseBase
{
public abstract void Spread();
}
public class Anthrax : DiseaseBase
{
public override void Spread()
{
GetPostedToPolitician();
}
}
public class BirdFlu : DiseaseBase
{
public override void Spread()
{
Cluck();
SneezeOnHuman();
}
}
public class SwineFlu : DiseaseBase
{
public override void Spread()
{
//roll in mud around other piggies
}
}
public class ManFlu : DiseaseBase
{
public override void Spread()
{
//this is not contagious
//lie in bed and complain
//get girlfriend to make chicken soup
//serve chicken soup with beer and baseball/football/[A-Za-z0-9]+Ball
}
}
public List<DiseaseBase> DiseaseCollection = new List<Disease>();
So everything gets stored in the collection as the base class (DiseaseBase), and with the appropriate use of abstract methods in the base and/or interfaces you can always handle each disease instance as the base object.

Categories

Resources