What is the difference between these two c# abstract classes? [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
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.

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

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 are the best practices for class, method, variable cases/names for objects in C# class library? [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
I'm a strong developer in some niche languages, and am organically learning C#, so trying to learn what are the best practices.
Can I get some feedback on what's best for the following sample code block where I'm building a Shopify integration for example.
namespace WMShopify
{
// Is it common to have the namespace and class the same?
public class WMShopify
{
// Are there different practices for private/public vars?
public string APIKey { get; set; } // Capital
public string password { get; set; } // lower case
public string secretString { get; set; } // Camel
private string _combinedVar; // Camel/underscore for private
}
// Should these be in a separate *.cs file?
public class WMShopifyOrders
{
// Method capital/lower/camel?
public int getOrderCount()
{
// lower/capital/camel?
int localMemberVar = 0;
return localMemberVar;
}
}
// Should these be in a separate *.cs file?
public class WMShopifyProducts
{
public List<string> getProductList()
{
return new List<string>();
}
}
}
Best practice: Come up with a standard that everyone agrees on and follows.
Verdicts: Written InLine
namespace WMShopify
{
// Is it common to have the namespace and class the same?
//No, namespace should probably be the name of the project itself.
public class WMShopify
//this looks like a configuration class
{
// Are there different practices for private/public vars?
public string APIKey { get; set; } // Capital
public string password { get; set; } // lower case
public string secretString { get; set; } // Camel
private string _combinedVar; // Camel/underscore for private
}
// Should these be in a separate *.cs file?
// I like to separate them because what happens when you have 100 classes, you just scroll forever?
public class WMShopifyOrders
{
// Method capital/lower/camel?
// I prefer capital
public int getOrderCount()
{
// lower/capital/camel? Sure
int localMemberVar = 0;
return localMemberVar;
}
}
// Should these be in a separate *.cs file? Yup
public class WMShopifyProducts
{
public List<string> getProductList()
{
return new List<string>();
}
}
}
While this question will likely end up getting closed, MSDN does provide pretty extensive guidelines that most .NET developers follow to some degree:
https://msdn.microsoft.com/en-us/library/ms229002(v=vs.100).aspx
Some highlights:
Don't use abbreviations; if you do use acronoyms, capitalize only the first letter, e.g. XmlReader, not XMLReader.
Use PascalCase for Methods and public Fields/Properties, use pascalCase for private fields, use _camelCase for private property backers.
Keep classes to one file - one exception would be defining an interface and its default implementation in the same file
Name methods using verbs (GetSomething(), SendSomething(), not Something()).
Don't name properties with Get or Set, e.g. Things is good but not GetThings
Name Booleans using "is" (IsEnabled, IsReadOnly, not Enabled).
Generic parameters should generally use T, or T(description), e.g. TSource, TKey, T1/T2/T3

Modifying variable from a derived class [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
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.

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