Which of the following code snippets performs fastest?
if(ClassTestBase is ClassTestChild1)
or
if(ClassTestBase.Type == EClassType.Child1)
Update:
Here is the full scenario:
public enum EInheritanceTree
{
BaseClass,
Child1,
Child2,
Child3
}
public class MyBaseClass
{
public virtual EInheritanceTree MyClassType
{
get
{
return EInheritanceTree.BaseClass;
}
}
}
public vlasse MyChildClass1 : MyBaseClass
{
public override EInheritanceTree MyClassType
{
get
{
return EInheritanceTree.Child1;
}
}
}
Consider a method that has to compare the class type to see what kind it is. Which is the best?
public bool IsChild1(MyBaseClass myClass)
{
if(myClass is MyChildClass1)
return true;
return false;
}
or
public bool IsChild1(MyBaseClass myClass)
{
if(myClass.MyClassType == EInheritanceTree.Child1)
return true;
return false;
}
Have you thought about using a profiler to test which is more performant yourself? Visual Studio comes with a profiler.
I would be more concerned about the need to have an enum that hold inheritance information about your application.
If you're worried about performance, don't wrap all this in functions. Any code that says:
if (Obj.IsChild1() ) foo;
Should just do:
if(myClass.MyClassType == EInheritanceTree.Child1) foo;
If you're worried about the performance, any notions you may have that says to hide everything behind functions needs to be revisited. Also, why don't you just use polymorphism - that's the "right" way to make subclasses act differently.
Regardless, do some timing of your own. It's the only way to be certain which is faster.
Related
I am developing a C# library where the user needs to write his/her own classes inheriting from given classes from the library. I don't think writing further details will be helpful, so please even if what I am asking for looks strange, consider it as such.
In one class, I would like the following behavior: two mutually exclusive "abstract" methods such that if one is implemented then there is no need to implement the other (so right, they are not really abstract).
I need to force the user to implement at least one of these methods, so declaring both methods virtual only is not enough. Actually I could declare both abstract, but it means the user should implement a method that would never be called afterwards and of course I want to avoid that.
Is there a trick or a C# idiom to do something close to what I want? Maybe with some reflection tricks I know almost nothing about?
I think what you're trying to do is violating a lot of Object-Oriented design goals.
"I need to force the user to implement at least one of these methods"
If the two classes need to have functionality that is is one thing or the other, why not just have 1 abstract method (or create an interface), and have the two classes override that method differently? Then you force each class to implement one part of the functionality and the other implement the other type.
I would recommend re-thinking your approach rather than spending tons of time trying to make a poor approach work.
EDIT:
Based on your comments I'll try to go into a bit more detail.
You could try something like the following. But I suspect you'll need to expand it significantly to get it working. But this should get you started anyway
public class ResultFromMethod1 {
public bool optimized = false;
// other results here
}
This stores the results from method 1 and tells you how method 1 was run.
public interface IInterfaceForMethod1 {
ResultFromMethod1 Method1 ();
}
public interface IInterfaceForMethod2 {
void Method2 (ResultFromMethod1 resultFromMethod1, Vector v);
}
These are the interfaces for the two methods. Note that they are not implemented yet. This is just a contract for classes that implement them.
public class UnoptomizedImplementation : IInterfaceForMethod1, IInterfaceForMethod2 {
#region IInterfaceForMethod1 implementation
public ResultFromMethod1 Method1 () {
ResultFromMethod1 resultFromMethod1 = new ResultFromMethod1 ();
resultFromMethod1.optimized = false;
// Method1 logic here
return resultFromMethod1;
}
#endregion
#region IInterfaceForMethod2 implementation
public void Method2 (ResultFromMethod1 resultFromMethod1, Vector v) {
if (!ResultFromMethod1.optimized) {
//if NOT optimized
//logic here
}
else {
//throw exception
}
}
#endregion
}
These class runs method1 not optimized, and then has a method2 that requires method 1 be not optimized. If you don't need method2 when it's not optimized then just don't implement the method2 interface.
public class OptimizedImplementation : IInterfaceForMethod1, IInterfaceForMethod2 {
#region IInterfaceForMethod1 implementation
public ResultFromMethod1 Method1 () {
ResultFromMethod1 resultFromMethod1 = new ResultFromMethod1 ();
resultFromMethod1.optimized = true;
// Method2 logic here
return resultFromMethod1;
}
#endregion
#region IInterfaceForMethod2 implementation
public void Method2 (ResultFromMethod1 resultFromMethod1, Vector v) {
if (ResultFromMethod1.optimized) {
//if optimized
//logic here
}
else {
//throw exception
}
}
#endregion
}
This class requires an output from method1 that is optimized or it throws an exception.
I hope that sends you down a more manageable track.
I suggest implementing interfaces
public interface IMyMethod1 {
void MyMethod1();
}
public interface IMyMethod2 {
void MyMethod2();
}
and inject a dependency
public class MyClass {
...
public MyClass(IMyMethod1 method1, IMyMethod2 method2) {
if ((null == method1) && (null == method2))
throw new ArgumentNullException("method1",
"You should provide either method1 or method2");
m_Method1 = method1;
m_Method2 = method2;
}
...
public void DoSomething() {
...
if (m_Method1 != null)
m_Method1.MyMethod1();
else if (m_Method2 != null)
m_Method2.MyMethod2();
...
}
}
To avoid reflection, create you base class (abstract) without either of those two methods.
Then, create separate classes (abstract) inheriting your base class for both of the "special" methods.
This will require some type-checking and casting, but it's all I got right now.
I have made some functions to control hardware. However in the event real hardware is present (G.demomode = true), I would like to also call the real hardware's functions, which implements the same interface.
You can see my attempt below, but the line DVDDHW.setSupply(voltage); isn't quite right, namely because a static class can't implement an interface. Is there a better way to do this?
The end goal is to define an interface (maybe this isn't the right word) to follow for the HW engineer so he can specify the unspecified functions in the interface.
I tried to do my due diligence of searching, and I found several threads on this topic. However, I couldn't wrap my head around how to implement their alternative solutions for my use case. Any help or pointers would be great.
Thanks!
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public static class DVDDHW : IPowerSupply
{
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
A singleton is the way to go if you only want one instance of a class that implements an interface.
The MS how-to is https://msdn.microsoft.com/en-us/library/ff650316.aspx.
For your code, the following will work:
public interface IPowerSupply
{
bool setSupply(double voltage);
}
public class DVDDHW : IPowerSupply
{
IPowerSupply _instance;
public static IPowerSupply Instance
{
get
{
if (_instance == null)
_instance = new DVDDHW();
return _instance;
}
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
public class DVDD : IPowerSupply
{
public bool setSupply(double voltage)
{
DevLog.DevLog.addToLog(string.Format("Supply set: {0}V: ", voltage) + this.GetType().ToString());
if (G.demoMode == false) //demoMode is false because HW is connected
{
DVDDHW.setSupply(voltage); //What is another way to accomplish this?
}
return true;
}
}
//Code to execute below:
foreach PowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
There are some slight differences in the way that the singleton behaves when compared to a static class. These are important if your application is multi-threaded, or if there is some other code in the constructor that you expect to run when the type is first accessed. If these things don't mean anything to you then you don't have to worry about it :)
EDIT:
As Scott pointed out, the code in the get accessor is unnecessary. A simplified version is this:
public class DVDDHW : IPowerSupply
{
static readonly IPowerSupply _instance = DVDDHW();
public static IPowerSupply Instance
{
get { return _instance; }
}
private DVDDHW() { }
public bool setSupply(double voltage)
{
i2c.write("DVDD ON"); //or something that involves turning the real hardware on
return true;
}
}
Also, this code had a typo (fixed):
//Code to execute below:
foreach IPowerSupply ps in PowerSupplyList // List contains an instance of DVDD in this example
{
ps.setSupply(3.5); // Set each supply to 3.5V
}
We're working with XML and want a common interface amongst the main XML class and all of its components. However, sub-components of the XML class need additional methods, but they also need the main component's methods. Seems like a great use for inheritance.
Here is some code I wrote to accomplish this task. Hopefully, you can get a good idea of what we're going for based on usage:
using System;
namespace SampleNamespace
{
public class SampleClass
{
public static void Main()
{
var xmlDocumentFiles = new XmlDocumentFiles();
xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml");
System.Console.WriteLine(
xmlDocumentFiles.Files.RootFile.GetFileName()
);
}
}
public class XmlDocumentFilesRoot
{
protected string _rootFileName;
public FilesClass Files { get { return (FilesClass) this; } }
}
public class FilesClass : XmlDocumentFilesRoot
{
public RootFileClass RootFile { get { return (RootFileClass) this; } }
}
public class RootFileClass : FilesClass
{
public void SetFileName( string newTitle )
{
_rootFileName = newTitle;
}
public string GetFileName()
{
return _rootFileName;
}
}
public class XmlDocumentFiles : RootFileClass
{
}
}
I was able to cast to child classes and to my surprise it runs just fine. Assuming nothing is put inside of the sub-classes other than methods which wouldn't make sense in the parent, will there ever be any problems (weird compilation errors, runtime crashes) with this class structure?
Are there any alternatives? I had initially tried nested classes + extension methods located outside of the main class, but there was a lot of code needed to set that up. See: https://stackoverflow.com/questions/19415717/using-c-sharp-extension-methods-on-not-in-nested-classes-to-establish-a-common
Extending functionality of a class, sounds like a decorator pattern.
Here's a head-first pdf on this subject:
http://oreilly.com/catalog/hfdesignpat/chapter/ch03.pdf
Also; I would like to discourage the triple '.' :
xmlDocumentFiles.Files.RootFile.SetFileName("Example.xml");
2 is evil, if you need 3: you will definitely lose maintainability.
Hope it helps.
I am unexperienced with Aspect-Oriented Programming. However, I've read a fair amount of PDFs and documentation available from PostSharp, and I think that I understand the gist of the paradigm. I have a pretty unique problem, and I believe AOP can be used to solve it. My predicament is as follows:
Many classes will inherit from A, which can be enabled or disabled. Consider B, which extends A. If B is disabled, I would like all method execution and property and variable access/modification to be disabled. That is, B.ExecuteMethod(); and B.Property = newValue; will have no effect if B is disabled. Furthermore, if one expects a return value, the value will be defaulted to 0 or null if B is disabled. That is, I would like to have expected default values for objects and values.
I am using the PostSharp C# library, which seems very powerful and well-developed. I believe my problem can be solved by means of AttributeInheritance. For example, A can be defined as:
[ModularAttribute(AttributeInheritance = MulticastInheritance.Multicast)]
public class A {
private bool m_enabled;
public A(){
m_enabled = true;
}
public bool Enabled() {
get {
return m_enabled;
}
set {
m_enabled = value;
}
}
}
and B can extend A. Moreover, my attribute, ModularAttribute can be defined as:
[Serializable]
public sealed class ModularAttribute : OnMethodBoundaryAspect {
public ModularAttribute() {
}
public override void OnEntry(MethodExecutionArgs args) {
// only execute code if enabled
}
}
This attribute will be applied to B because B extends A.
The root of my problem is: I need ModularAttribute to reference A's Enabled property, such that OnEntry will only execute code if Enabled is true. Since this is a class-level aspect, I cannot parameterize a wrapped version of m_enabled to ModularAttribute since it is out of scope.
Is there a way that I can tell ModularAttribute that all of its owners will implement a specific interface? If so, could ModularAttribute access the specific properties from said interface? If so, this would solve my problem.
To clarify, I would like to "tell" PostSharp: "The class that uses ModularAttribute is guaranteed to implement C. So, let ModularAttribute access whatever C defines because it's ensured to work."
C can be defined as:
public interface C {
public bool Enabled();
}
Thus, in ModularAttribute, I could do something along the lines of
if (attachedClass.Enabled == false) {
// don't execute code
} else {
// execute code
}
This problem can be perceived as authentication on the per-object level rather than the more typical per-user level. Having to add an if, else check on every Property and Method that extends A seems like a cross-cutting concern. Thus, I think AOP is a fitting choice for this problem; however, because of my inexperience with this paradigm, I might be approaching it the wrong way.
Any guidance would be much appreciated. Thanks for the help,
I'm a little concerned that this much inheritance could be a design flaw or at least a huge maintenance headache, but assuming that it's not, let's soldier on...
I don't think there's a way to do exactly what you want to do. Even if PostSharp had the ability, C# needs to know the type at compile time (before PostSharp even touches it).
I suggest that you use CompileTimeValidate to verify that the class the aspect is used on is of a certain type, and once that's in place, you can cast args.Instance to your interface type without worrying about an invalid cast exception. And if that class doesn't implement IEnabled, then you'll get a compile-time error.
Here's a quick example:
public interface IEnabled
{
bool Enabled { get; }
}
[Serializable]
public class ModularAttribute : OnMethodBoundaryAspect
{
public override bool CompileTimeValidate(System.Reflection.MethodBase method)
{
if(typeof(IEnabled).IsAssignableFrom(method.DeclaringType))
return true;
Message.Write(method, SeverityType.Error, "MYERR001", "Aspect can't be used on a class that doesn't implement IEnabled");
return false;
}
public override void OnEntry(MethodExecutionArgs args)
{
var obj = (IEnabled) args.Instance; // this will always be a safe cast
if(!obj.Enabled)
args.FlowBehavior = FlowBehavior.Return;
}
}
There's a catch though: you don't want this aspect being used on the Enabled property itself, because that would cause a stack overflow (i.e. the aspect checks the property, causing the aspect to check the property, etc). So make sure to exclude Enabled using AttributeExclude.
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Enabled = false;
b.SomeMethod();
b.AnotherMethod();
}
}
public interface IEnabled
{
bool Enabled { get; }
}
[Modular(AttributeInheritance = MulticastInheritance.Multicast)]
public class A : IEnabled
{
[Modular(AttributeExclude = true)]
public bool Enabled { get; set; }
public void SomeMethod()
{
Console.WriteLine("in SomeMethod");
}
}
public class B : A
{
public void AnotherMethod()
{
Console.WriteLine("in AnotherMethod");
}
}
I don't know:
if this works.
if it's a good idea.
what it is called in order
to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:
var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.
I think the idea of having an OrNew method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about it
Don't have a hidden flag that controls the behavior (ThrowIfNull). This makes it impossible for someone to read an OrNew call an understand what it does.
Use a new constraint in favor of the less safe Activator.CreateInstance<T>() call
I'd call it something other than DebugLogic. Generally (but not always) extension method containers end with the Extensions .
For example
public static class LogicExtensions {
public static T OrNew<T>(this T obj) where T : class, new() {
if (obj != null) {
return obj;
}
return new T();
}
}
The name of this operation is clearly: DefaultIfNull