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();
}
Related
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 5 years ago.
Improve this question
I'm looking for a clean way to run a method that could have different implementations from within a static method.
The reason for this requirement is that I would like access to a static method A that will always call method B. The implementation of method B however might be different.
Simple example of the code is as follows.....
public class PageFactory
{
public static void InitializeElements()
{
new PageFactory().Initialize();
}
public virtual void Initialize()
{
Console.WriteLine("Page factory initialize");
}
}
public class SepaPageFactory : PageFactory
{
public override void Initialize()
{
Console.WriteLine("SEPA Factory initialize");
}
}
class Program
{
static void Main(string[] args)
{
// "Page factory initialize"
PageFactory.InitializeElements();
// I would like to see "SEPA Factory initialize here"
SepaPageFactory.InitializeElements();
Console.ReadLine();
}
}
Obviously SepaPageFactory.InitializeElements(); doesn't return the result I would like.
This is the first option I considered
public static void InitializeElements(PageFactory factory)
{
factory.Initialize();
}
And then do...
PageFactory.InitializeElements(new PageFactory());
PageFactory.InitializeElements(new SepaPageFactory());
Also I could do...
public static void InitializeElements<T>() where T : PageFactory, new()
{
new T().Initialize();
}
And...
PageFactory.InitializeElements<PageFactory>();
PageFactory.InitializeElements<SepaPageFactory>();
Is there a better way of achieving this?
I'm open to any design suggestions that solve this problem.
EDIT
I'll try to describe the actual use case.....
This is to be part of a test automation framework where elements on a webpage are represented by fields in a class. These 'page' classes can have upwards of 50 elements that all require instantiating. As they all have the same constructor parameters, a quick and clean way to do this (IMO) is with reflection.
The 'real' initialize method will be used to reflect over and instantiate certain fields on these pages.
Using my generics implementation above it would look like...
public static void InitializeElements<U,T>(IWebDriver driver, T page) where U : PageFactory, new()
{
new U().Initialize(driver, page);
}
public virtual void Initialize<T>(IWebDriver driver, T page)
{
var pageType = typeof(T);
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.DeclaredOnly;
foreach (var field in pageType.GetFields(flags))
{
var findsByAttribute = (FindsByAttribute)field.GetCustomAttribute(typeof(FindsByAttribute));
var frameAttribute = (FrameLocatorAttribute)field.GetCustomAttribute(typeof(FrameLocatorAttribute));
var fieldType = field.FieldType;
if (fieldType.IsSubclassOf(typeof(Control)) || fieldType == typeof(Control))
{
field.SetValue(page,
frameAttribute != null
? InitializeControls<Control>(field, driver, findsByAttribute, frameAttribute)
: InitializeControls<Control>(field, driver, findsByAttribute));
}
}
}
U in this context is the class that provides the implementation of the Initialize method.
Most of the time this implementation will be sufficient, however on occasion there will different constraints on which field types are instantiated, hence the need for virtual/override.
This would then be used in the constructor of the pages where I wish to initialise all my fields, e.g....
public class LoginLinkPage : BasePage<LoginLinkPage>
{
[FindsBy(".content a[href='/Account/SignIn']", How.CssSelector)]
public Control LoginLink;
public LoginLinkPage(IWebDriver driver) : base(driver)
{
PageFactory.InitializeElements<SepaPageFactory, LoginLinkPage>(driver, this);
}
}
Which I would like to be consistent regardless of which implementation of Initialize is to be used.
Well, this shouldn't be the best way, but you can also do something like this:
public class Foo
{
public static void DoWork(int a)
{
}
}
public class Doh : Foo
{
public **new** static void DoWork(int a)
{
}
}
That should "override" the method, but maybe it would be better to think about different approach :)
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
An example:
class E
{
public static E e;
//...
};
What's the functionality of this or under which circumstances should we use this? Thanks.
One of usages can be to implement singleton (When you need a class that has only one instance, and you need to provide a global point of access to the instance): Implementing Signleton
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
A static variable cannot hold a reference to anything else that is declared in an instance, but rather a static variable/method belongs to the type instead of an instance of a type.
Consider this:
public class TestClass
{
private static string _testStaticString;
private string _testInstanceString;
public void TestClass()
{
_testStaticString = "Test"; //Works just fine
_testInstanceString = "Test";
TestStatic();
}
private static void TestStatic()
{
_testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
_testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
}
}
The many usages are so many it could fill books. As someone mentioned, the Singleton pattern makes use of it.
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.
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 am trying to verify whether can i cast abstract and interface class . I have tried the following but can't get it so I assume I'm going about it the wrong way.
Your question is a bit vague. There can be quite a few possibilities to your question. I have tried to give them here. See if it fits your needs. If not then please comment
Building of class structure
public abstract class MyAbClass
{
public abstract void MyM1();
}
public interface IMyInterface
{
void MyM2();
}
public class MyConcretClass1 : MyAbClass
{
public override void MyM1()
{
//Your implementation here
}
}
public class MyConcretClass2 : IMyInterface
{
public void MyM2()
{
//Your implementation here
}
}
Possibilities
//Following are the possibilities
//This can be done in some other class and passed to some other method
//maybe a factory pattern
MyAbClass cls1 = new MyConcretClass1();
//Will call method of MyConcretClass1
cls1.MyM1();
if (cls1 is MyConcretClass1)
{
//Do casting here
}
var cls2 = cls1 as MyConcretClass1;
if (cls2 != null)
{
//Do your stuff here
}
//This can be done in some other class and passed to some other method
//maybe a factory pattern
IMyInterface cls3 = new MyConcretClass2();
//Will call method of MyConcretClass2
cls3.MyM2();
if (cls3 is MyConcretClass2)
{
//Do casting here
}
var cls4 = cls3 as MyConcretClass2;
if (cls4 != null)
{
//Do your stuff here
}
Hope this helps
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.