This question already has answers here:
C# .Equals(), .ReferenceEquals() and == operator
(7 answers)
Closed 7 months ago.
I need to complete the piece of code to write a method that takes a factory method that returns an object and determines if the object is a singleton instance.This is for an exercise of a course i am taking about design patterns. All the previous exercises were about implementing the pattern but this one is about testing and i dont know how to test this. I tried to create another instance and check if the hashcodes are the same but i dont know how to create another instance with that function.
public class SingletonTester
{
public static bool IsSingleton(Func<object> func)
{
// todo
}
}
Singleton is a semantic definition, it is not generally testable through code. No interface can guarantee that the class operates as a singleton.
Because of the semantic nature it would be better to create a custom annotation to indicate if the object is a singleton.
Related
This question already has answers here:
How do I instantiate a class given its string name?
(3 answers)
Create an instance of a class from a string
(8 answers)
Closed 1 year ago.
I have a database-driven application that runs different surveys. Most of the behaviour of each of the surveys is similar and can be represented using common patterns. But occasionally, I would like to have some special code to implement some of the functionality for a particular survey.
Now, this is done like this:
switch (SurveyId.ToLower())
{
case "surveya":
_testModule = new SurveyA(this);
await _testModule.Init();
break;
case "surveyb":
_testModule = new SurveyB(this);
await _testModule.Init();
break;
default:
break;
}
So basically with a switch identifying the exceptions.
Later in this code, I call some methods on the _testModule class.
I understand I could do this by overriding a base implementation. Then I would not have this switch, but I would call the standard method, and have this overridden in a derived class. But that would mean the same switch comes at a higher level, calling a class that overrides the base class instead of the base class itself. Basically, it would just move this switch-up in the stack, but it would not reduce complexity.
At other points in the code in a web API, inheritance does not seem to help at all, and I see no other way than this switch.
So what is the best way to handle this?
This question already has answers here:
C# virtual keyword
(9 answers)
C# - Keyword usage virtual+override vs. new
(11 answers)
Can you write virtual functions / methods in Java?
(6 answers)
Closed 4 years ago.
In an interview it was asked why do we need to override method of base class.
I tried to answer like when we want to have different implementation in derived class.
But then he said, "Why don't we just create a new method with different name and different implementation instead of overriding base class method?", anyway we are not reusing base class method as implementation will be different then just create a new method instead of overriding.
I got confused what to answer. Could somebody explain.
public class BaseClass
{
virtual void Foo(){}
}
public class DerivedClass: BaseClass
{
override void Foo(){}
}
Generally we implement overriding like above.
What he said is like why do we need concept of overriding we can do like below
public class BaseClass
{
void Foo(){}
}
public class DerivedClass: BaseClass
{
void Foo1(){}
}
His question was looking weird I tried to explain but like its a method of base class we are just redefining it in derived class. In this way our code will be clean as well. But looks like he was not satisfied.
I would check this answer:
Why does this polymorphic C# code print what it does?
then try to grasp the concept of methods in an object basically having pointers to code. When you override implementation in an subclass then that becomes the new code pointed to, whether it's used or cast as a superclass or not.
So the main purpose of overriding is to create classes that inherit from one class but each have their own implementation and then be able to treat or operate on them equally the same as the original superclass. This is the essence of the Liskov Principle or the 'L' in SOLID. What is an example of the Liskov Substitution Principle?
This question already has answers here:
What is the difference between getter-only auto properties and expression body properties?
(2 answers)
Closed 7 years ago.
I have a class that uses some services. I need each service to be instantiated on creation of the class. In C# 6 I can see 2 ways of doing this but I'm not sure which would be correct...
protected static SomeServiceType Service => new SomeServiceType();
alternatively I could use an autoproperty initialiser...
protected static SomeServiceType Service { get;} = new SomeServiceType();
What are the advantages/drawbacks with each approach?
Many thanks
I believe
the former ("Expression-bodied members") calls new SomeServiceType() every time the property is read
the latter ("Auto-property initializers") calls it once on instantiation, and returns the created instance every time the property is read.
It sounds like you want the latter.
This question already has answers here:
How to call base.base.method()?
(13 answers)
Closed 8 years ago.
In .NET I am trying to monkey-patch a 3rd party library. I created a new class, Grandchild, which inherits from a class Child derived from Parent. In an override method of Grandchild, I need to skip Child and invoke Parent. Is that possible? In other words, I want to do:
public class Grandchild : Child {
public void override MyMethod() {
// illegal syntax examples, but how can I invoke Parent.MyMethod?
base.base.MyMethod(); // nope...
Parent.MyMethod(); // nope...
}
}
That simply cannot be done, not even with reflection, and for a very good reason - security.
If a class you distributed enforced some business rules, and clients were able to skip those rules, you could run into a huge security hole. Such basic polymorphism rules simply cannot be violated.
Security is also why expression trees cannot contain references to base, as explained by Eric Lippert here.
//this is illegal
Expression<Func<string>> nonVirtualCall = () => base.Method();
This question already has answers here:
Which objects can I use in a finalizer method?
(3 answers)
Closed 8 years ago.
I have code like this:
~MyClass() {
try {
if (Database.Exists(_connectionString))
{
Database.Delete(_connectionString);
}
} catch { }
}
Database is a static class of Entity Framework, whereas _connectionString is a private readonly string set by the ctor. The idea is that if someone forgot to Dispose the class, we still clean state (in my case, this is part of an integration test where the test runner doesn't call Dispose if there's an unhandled exception in the test, so it's not something I can fix on my side)
However, Finalizers are generally not supposed to call class members because they might be disposed already, so if I end up in a scenario where the _connectionString is already collected, I might have a problem.
Is there a way to do this safely (e.g,, using some sort of GC.KeepAlive construct?)
Edit
As pointed out, below was not a direct answer to the question so....
Yes it is safe to access the member variables (in this particular example - assuming the connection string is a string) and in addition I recommend you check out the IDisposable pattern.
Original
You should implement the IDisposable pattern:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
This will ensure that the Dispose method is always called and you can safely access the member variables.