How to implement this C# class hierarchy - c#

What I want to do is really simple. I have a class which handles my database executions called clsSQLInterface. This class contains a static function called bool isSQLSafe which will return false if the SQL being sent for execution is considered dangerous. This is so I have one point where I can filter out any malicious goings on.
Now, another part of my program actually needs to be able to do things like UPDATE, DELETE etc. So I thought I would inherit the clsSQLInterface class and override the isSQLSafe function with something that always returns true.
This isn't a question about database secutrity btw!
Ok so I did this like this...
public class clsSQLInterface //Code not shown, just definitions
{
private static string connectionString(string sKey){...}
public static bool isSQLSafe(string sSQL){...}
public static DataTable executeSQLText(string sSQL, string sConnectionKey){...}
public static DataTable executeGenericQuery(clsGenericSQL query,string sDBKey){...}
}
And the overriding class..
public class clsSQLInterface_unsafe : clsSQLInterface
{
public clsSQLInterface_unsafe()
{
}
public new static bool isSQLSafe(string sSQL) //overriding the base method
{ return true; }
}
Ok. The problem with this approach is that isSQLSafe is called from within the methods executeSQLText and executeGenericQuery. What I want these methods to do is call the overridden isSQLSafe which always returns true. However, they don't. They call the base implementation.
Do I also have to override every method which calls isSQLSafe? This seems like a waste of code.
Surely when I inherit the class I am effectively 'copying' all the base methods and they should behave as though they are now part of clsSQLInterface_unsafe?

You cannot override static methods. They are not inherited, they are methods of the class, not of an instance of the class. A static method in the base class will always call the static method in the same class.
Just making the methods not static and virtual, then overriding them in the derived class should solve your problem.
EDIT: the new static modifier just tells the compiler that you intend to hide the method of the base class (try to remove it and see the warning you get), but it does not override anything.
Overriding means that the derived class version of the function is taking the place of the base class version in the virtual table.
The virtual table is an index of the methods associated to an instance. No instance, no virtual table, therefore you cannot override a static method.
P.S: have a look at a better explaination of what is a virtual table here: http://en.wikipedia.org/wiki/Virtual_method_table

The problems comes from the static modifier.
You may reconsider refactor your code using, why not, something like this :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class BaseSqlInterface
{
protected abstract bool IsSafe(string instruction);
public void Execute(string sqlStatement)
{
if (IsSafe(sqlStatement))
{
// run the sql command
}
else
{
throw new Exception("You're evil");
}
}
}
public class SqlInterfaceSafe : BaseSqlInterface
{
public override bool IsSafe(string instruction)
{
return instruction.Contains("I'm not evil, I promise");
}
}
public class SqlInterfaceUnsafe : BaseSqlInterface
{
public override bool IsSafe(string instruction)
{
return true;
}
}
public static class SqlInterfaceFactory
{
public static BaseSqlInterface GetInstance()
{
// return the actual object using IOC, switch, ... whichever method you want
return DateTime.Now.Day % 2 == 0 ? (BaseSqlInterface)new SqlInterfaceSafe() : new SqlInterfaceUnsafe();
}
}
}

Related

C#: Protected Variables inside of a Generic Class can be accessed by a different subclass of that Generic Class. Can I prevent this?

Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
Declare it as readonly in the base class if possible.
Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string[] args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}

Scenario Based Query: Skipping validation for a class without using IF condition

Consider you have the following classes: Class1, Class2 .... Class1000.
All the classes are inheriting interface IClass.
All the classes can be validated using below code
Validate(IClass class)
{
}
How can we skip validation for class 200 to class 300 (these numbers can vary, so no logic using numbers) without using if condition?
Personally, i'd move your validate check into the model.
E.g.
public interface IClass{
bool ShouldValidate();
}
Then, in each class:
public class Class200
{
public bool ShouldValidate() => false; // because whatever
}
Then in your validate:
public void Validate(IClass class)
{
if(class.ShouldValidate())
{
// do whatever
}
}
This way the logic belongs to the IClass instances, and anyone willing to extend this knows exactly how to implement the exception.
Also, for classes 200-300, you can inherit them from a common base class that always returns false to have a DRY pattern.
Update Another option is putting validate inside the class directly, e.g. like so:
public interface IClass{
void Validate();
}
Then just leaving the method empty in classes 200-300, e.g.
public class Class200
{
public bool Validate()
{
}
}
and implement where needed
public class Class1
{
public bool Validate()
{
// do awesome things here
}
}

Exercise: Implement an abstract class

So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.
and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.
the code that you start with is:
using System;
// Implement your classes here
public class Program
{
public static void Main()
{
}
}
so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things
using System;
// Implement your classes here
public abstract class SpaceStation
{
public abstract void FireLaser();
}
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
return Console.WriteLine("Pew pew");
}
}
public class Program
{
public static void Main()
{
}
}
So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.
Remove the return statement from the overridden FireLaser method:
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
A method marked as void does not return anything. The return keyword is usually used to return a result from a method. Therefore it usually does not make sense in a void method. Removing the return keyword from your statement will resolve your compiler error.
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
Note that the return keyword can be used in a void method to end the method. However, its usage is generally discouraged because it can result code that returns from multiple places and this can be confusing. When used in this manner, you still do not return an actual value. return would be the only part of the statement. Consider the following code:
public void ProcessSomeWork(SomeWork work)
{
if(work.IsCompleted)
{
return;
}
work.DoSomething();
DoSomethingElseToWork(work);
}

Implementing Interface using extension methods in c#

I have an Interface:
public interface IMessager
{
void ShowMessage();
}
Is there any way to implement this interface using extension methods?
public static class Extensions
{
public static void ShowMessage(this MyClass e)
{
Console.WriteLine("Extension");
}
}
and a class that implement it:
public class MyClass:IMessager
{
public void ShowMessage()
{
ShowMessage(); // I expect that program write "Extension" in console
}
}
But when I run the program I get the System.StackOverflowException.
The code you posted is just a method calling itself recursively (hence the StackOverflowException).
I'm not entirely sure what you're trying to accomplish but to answer your question
Is there any way to implement this interface using extension methods?
No.
To be a bit more pragmatic about this though, if your aim is to only write your method once you have a few options:
1. Call the extension explicitly
public class MyClass:IMessager
{
public void ShowMessage()
{
Extensions.ShowMessage(this);
}
}
although as pointed out in comments, this basically defeats the point of using the extension method. Additionally there is still "boiler-plate code" such that every time you implement your interface you have to call the static method from within the method (not very DRY)
2. Use an abstract class instead of an interface
public abstract class MessengerBase
{
public void ShowMethod() { /* implement */ }
}
public class MyClass : MessengerBase {}
...
new MyClass().ShowMethod();
This issue with this though is that you can't inherit from multiple classes.
3. Use extension on the interface
public interface IMessenger { /* nothing special here */ }
public class MyClass : IMessenger { /* also nothing special */ }
public static class MessengerExtensions
{
public static void ShowMessage(this IMessenger messenger)
{
// implement
}
}
...
new MyClass().ShowMessage();

C# Alternative to virtual static methods and static sub classes

Whenever I read questions RE this, or a similar topic of static inheritance, the replies are usually that this is not supported (we know that), and the reason is given as being because this is a poor design and there's probably a better way to do it. I'd love to find a better way of doing it so am open to all suggestions - here's what I am trying to do.
I have a class which has no instance data. All the methods are static. Let's call this class BaseStatic. I now want a new static class (well several of course but lets stick to one) which inherits from this static class and adds some new static methods, let's call this SubStatic.
What I want consumers to be able to write is:
SubStatic.MethodFromSub();
and also
SubStatic.MethodFromBase();
I know I could also write:
BaseStatic.MethodFromBase()
explicitly but then consumers have to know which class implements which methods. I can't do this with inheritance because I can't inherit one static class from another. So what's a better way of doing it?
Now, I know I can have these classes as instance classes, and I can define all the methods as static - that will give me the behaviour I described above but leads to other problems, namely:
When I do this:SubStatic.MethodFromBase() the SubStatic static constructor is not called because the method is running in the parent static class (the parent's static constructor is called)
If one of the static parent methods needs to call another method which the sub class can override, I need a virtual static method in the sub class. Which I know I can't have.
So poor design apparently - can anyone help me redo it? I know I can use instance inheritance and take proper use of virtual methods (I've had it working this way) but client code then always has to create an instance (or I suppose some singleton).
This could serve your purpose, though I certainly would include some exception handling and accompany its implementation with a great deal of documentation as to why and how it works.
When the static constructor for Base is run (once) all assemblies that are currently loaded in the app domain are catalogued, selecting the types that derive from Base. Iterating over those, we run the static constructors. It is worth noting though, that this no longer guarantees the cctor for each implementation will be run exactly once, logic would have to be added to each of them to re-make that assertion. Moreover, types that are loaded after the cctor for Base has been run would not be initialized by calls to methods in Base
To simulate virtual methods, use the new keyword to hide the base method. You can call the base method by qualifying it with the declaring class's name (like in class B in the example)
using System;
using System.Linq;
using System.Runtime.CompilerServices;
namespace ConsoleApplication6
{
public class Base
{
static Base()
{
Console.WriteLine("Base cctor");
var thisType = typeof (Base);
var loadedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes());
var derivations = loadedTypes.Where(thisType.IsAssignableFrom);
foreach(var derivation in derivations)
{
RuntimeHelpers.RunClassConstructor(derivation.TypeHandle);
}
}
public static void Foo()
{
Console.WriteLine("Bar");
}
}
public class A : Base
{
static A()
{
Console.WriteLine("A cctor");
}
}
public class B : Base
{
static B()
{
Console.WriteLine("B cctor");
}
public new static void Foo()
{
Console.WriteLine("Bar!!");
Base.Foo();
}
}
class Program
{
static void Main()
{
Console.WriteLine("A:");
A.Foo();
Console.WriteLine();
Console.WriteLine("B:");
B.Foo();
Console.WriteLine();
Console.WriteLine("Base:");
Base.Foo();
Console.ReadLine();
}
}
}
EDIT
Another option lies in the CRTP (or CRGP in the C# paradigm) or curiously recurring template (generic) parameter pattern
using System;
using System.Runtime.CompilerServices;
namespace ConsoleApplication6
{
public class Base<T>
where T : Base<T>
{
static Base()
{
RuntimeHelpers.RunClassConstructor(typeof (T).TypeHandle);
}
public static void Foo()
{
Console.WriteLine("Bar");
}
}
public class Base : Base<Base>
{
}
public class A : Base<A>
{
static A()
{
Console.WriteLine("A cctor");
}
}
public class B : Base<B>
{
static B()
{
Console.WriteLine("B cctor");
}
public new static void Foo()
{
Console.WriteLine("Bar!!");
Base<B>.Foo();
}
}
class Program
{
static void Main()
{
Console.WriteLine("A:");
A.Foo();
Console.WriteLine();
Console.WriteLine("B:");
B.Foo();
Console.WriteLine();
Console.WriteLine("Base:");
Base.Foo();
Console.ReadLine();
}
}
}
In this case, when we call a static method on A we're really calling it on Base<A> which is different than Base<B> or Base so we can actually determine how the method was called and run the appropriate cctor.
You can achieve this by using Generics. For example you can use something like that:
public class MainStatic<T> where T : MainStatic<T>
{
public static void Foo()
{
}
static MainStatic()
{
RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
}
}
public class SubStatic : MainStatic<SubStatic>
{
public static void Bar()
{
}
}
public class Instance
{
public void FooBar()
{
SubStatic.Foo();
SubStatic.Bar();
}
}

Categories