I have a class and a method inside it. I want to use two different attributes.
[TokenValidate]
public class Auth
{
[NoTokenValidate]
Public void methodname()
{
}
}
I want that to disallow one particular method to use the parent class attribute. Is it possible?
Related
I want to write a framework which needs to implement a few functions. Now I need to access the base class functions from the framework, which does not work.
I need to inherit form a given class "Master"
public class MyClass : Master
{
protected override void Initialize() {
FunctionInMaster();
VariableInMaster = true;
}
}
Now I simply want to create a class that can be derived and implements Master functions.
public class MyFrameworkClass
{
// framework override
public void whatever()
{
FunctionInMaster();
VariableInMaster = true;
}
}
public class MyClass : Master
{
protected override void Initialize() {
whatever();
FunctionInMaster();
VariableInMaster = true;
}
}
How do I do that without instantiating "MyFrameworkClass" and passing a pointer of "this" to MyFrameworkClass?
You can never have multiple inheritance in C# (and it's a very good thing, multiple inheritance is a nightmare), but you can invoke methods from other classes, or even have some composition.
public static class MyFrameworkClass
{
// framework override
public static void whatever(Master master)
{
master.FunctionInMaster();
master.VariableInMaster = true;
}
}
public class MyClass : Master
{
protected override void Initialize()
{
MyFrameWorkClass.whatever(this);
FunctionInMaster();
VariableInMaster = true;
}
}
Don't try to do too many things with inheritance. Inheritance is a powerful tool, but not an universal one. Often composition is better suited to tackle a specific problem.
You could also have multiple levels of inheritance, if you need to access protected methods and you know you will reuse this code in other derived classes.
public class MyFrameworkClass : Master
{
// framework override
protected void whatever()
{
FunctionInMaster();
VariableInMaster = true;
}
}
public class MyClass : MyFrameworkClass
{
protected override void Initialize()
{
whatever();
FunctionInMaster();
VariableInMaster = true;
}
}
Although you could change inheritance to be Master -> MyFrameworks -> MyClass, that is less advisable. Is the intention to make sure deriving classes implement specific methods - in that case consider adding abstract methods to Master. If you are unable to alter Master, you can change MyFrameworks to be an interface rather than a class. MyClass can inherit multiple interfaces, but only one class.
I need to access the base class [instance] functions from the framework
To call instance methods you need an instance. There are three ways to do that:
Inherit form the class and use this - you have already stated that you can't do this.
Accept an instance of the base class and call methods on it - you have stated that you don't want to do this.
Create an instance of the class and call methods on it.
Now static methods are different - you do not need an instance, but they can only use static fields, which would be shared across all instances of the class. Since you use a non-static property in the base class, it's safe to assume that static is not an option, so you're stuck with one of the three options above.
Within my projects I often want to have a method (or function if you prefer) that is private, however I also want to access it from ONE other class. Is this a possibility?
To clarify, this method can be accessed from ClassA, its own class but not any other.
There are plenty of ways to do this untill your last statement that is "and ONLY that class", i can only think of 1 way to do that and it is to have the classes laid out in assemblies as such as such:
Assembly A only contains class A with the method you want declared as internal
Assembly B declared as a friendly assembly : https://msdn.microsoft.com/en-us/library/0tke9fxk.aspx and contains code to call A (it can as to it it is internal as if in the same assembly as it is a friend assembly)
No other assembly linked to A , B or both will be able to call the method on class A as it is internal.
The best way that I can think of is this.
In C# 5, a set of caller information attributes were added, namely [System.Runtime.CompilerServices.CallerMemberName], [System.Runtime.CompilerServices.CallerFilePath], and [System.Runtime.CompilerServices.CallerLineNumber]. We can use the CallerFilePathAttribute to see whether the caller comes from a particular .cs file.
Usually, one file will only contain one class or struct. For example, ClassA is defined in ClassA.cs. You can check if the caller file name matches ClassA.cs in the method.
So modify your method's parameters like this:
([CallerFilePath] string callerFilePath = "" /*Other parameters*/)
In the method, check if the callerFilePath matches the file path of ClassA. If it does not, throw an exception saying that the method can only be accessed from ClassA!
You can make this method protected, if it suits your OOP structure:
public class A
{
protected void Test()
{
Console.WriteLine("I can only be called from B");
}
}
public class B : A
{
public void Pub()
{
Test();
}
}
And there many other ways to do this.
However, in general, it sounds like a wrong look at access modifiers.
If you want to only call your method from exactly one place, then just call it from exactly one place.
The fact that this method should be called from another class, makes him public, logically and architecturally.
Another simple way to control member access is using delegates.
Let's assume you have a private method:
class SecureMethod {
private void DoSomething() { }
}
You can provide access to this method by injecting delegate to this method:
class ClassA {
public ClassA(Action secureMethod) { }
}
SecureMethod objWithSecureMethod;
var a = new ClassA( objWithSecureMethod.DoSomething );
I'm showing you how do to this, but these are very bad practices:
public class A
{
private void CanOnlyCallMethodInClassB();
public static void SetHandlerCanOnlyCallMethodInClassB(ClassB b)
{
b.MethodFromClassA = CanOnlyCallMethodInClassB;
}
}
public class B
{
public Action MethodFromClassA { get; set; }
}
in code:
var b = new B();
A.SetHandlerCanOnlyCallMethodInClassB(b);
b.MethodFromClassA();
but better way is to use object of ClassB in method's classA. Search google for strategy pattern or use inheritance.
Whatever you are asking is not possible in C#. I mean you can not allow only one class to use private method. All you can do is to use internal which allows classes of just one assembly to access your methods or protected which is accessible within its class and by derived class instances!
Apart from that There is not any thumb rule for what you are asking but you can do some hack as shown below:
MethodInfo privateMethod = instance.GetType().GetMethod("NameOfPrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
privateMethod.Invoke(instance, new object[] { methodParameters });
One slightly dirty trick to use a method from class B in class A is to make the method protected rather than private and derive A from B.
Another possibility, probably better, is to make the method internal rather than private and then put class A and B in the same assembly.
I am working on a project that uses Canvas objects. I would like to add a few functionalities to manipulate them.
Until now, I was adding them in a CanvasUtils class but now I realize that I could actually create a CustomCanvas class that would inherit from Canvas and implement the new functionalities.
I can feel the second way is more intuitive but I am not sure whether it is the best option or not.
For example, if I keep adding new methods to a CustomCanvas class it is going to become huge at some point whereas I can easily break a utils class into several ones.
Also a Utils class sounds more independent and extendable to me. For example, if I wanted to extend some of the functionalities to Panel objects (Canvas inherits from Panel), I think it would be easier to do it with a Utils class as you just have to change the Canvas references to Panel.
My questions are:
what are the advantages and flaws of each method and
when should I use one over another?
If you are adding new functionality, then you should extend the class. You'll be able to add your own state, as well as methods to interact with them. However, you won't be able to add this functionality to existing objects.
If you are simply writing shortcuts that use existing functionality, then you can use Extension Methods to add functions without needing to extend the class. For example...
public static class PanelExtensions
{
public static void DoSomething(this Panel panel)
{
panel.SomePanelMethod();
panel.SomeOtherPanelMethod();
}
}
And then to use this...
Panel myPanel = new Panel();
myPanel.DoSomething();
The advantage of this approach is that the methods are available to existing panels, and they will be inherited too (so your Canvas objects will receive these methods too).
Note than in order to use extension methods, you need to have a using statement at the top of your file referencing the namespace in which they are defined.
It depends on what you are trying to achieve and what do you need to implement new functionality:
If you have stateless methods that do not need any additional information associated with object, then you can either continue to use Util methods or turn them into Extension methods that will give you both the inheritance-like feel of use and loose coupling of the Util class:
public static class CanvasExtensions
{
public static void TransformElements(this Canvas canvas,
Action<CanvasElement> transform)
{
...
foreach(var elem in canvas.Children)
{
transform(elem);
}
...
}
}
If you need to associate some piece of info with the object you operate on, then:
you can either inherit the class if the object's behaviour shall be deeply affected by additional functionality (like when other standard methods can negate new functionality) to allow base function overriding:
public class DeeplyAffectedCanvas : Canvas
{
private IDictionary<CanvasElement, Action> m_dictionary;
public void SpecialTransform(CanvasElement elem, Action transform) { }
public override void Resize()
{
// Resize, for example, have to take into account
// the special operation
}
}
or create a wrapper, that exposes the original object (Panel) when the additional behaviour doesn't affect the wrapped object much:
public class Wrapper<T>
{
public Wrapper(T wrapped)
{
this.Wrapped = wrapped;
}
public T Wrapped { get; private set; }
public implicit operator T (Wrapper<T> wrapper)
{
return wrapper.Wrapped;
}
}
public class WrappedCanvas : Wrapper<Canvas>
{
private Object data;
public void SafeTransform(...);
}
I have partial class User generated by LINQtoSQL as shortly following:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.[User]")]
public partial class User : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
...
Then I created separate folder "Proxy" in my project and put there extra piece of User class:
namespace LINQtoSQL_sample.Proxy
{
public partial class User
{
public static string GetActivationUrl()
{
return Guid.NewGuid().ToString("N");
...
Issue happens when I try to invoke that extra static method from another part of same project. Let's say I have once more folder "SqlRepositoryImpl" and another one partial class there:
namespace LINQtoSQL_sample.SqlRepositoryImpl
{
public partial class SqlRepository
{
public bool CreateUser(User instance)
{
if (instance.ID == 0)
{
instance.added_date = DateTime.Now;
instance.activated_link = LINQtoSQL_sample.Proxy.User.GetActivationUrl();
...
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
Please, advise why such happens and where I'm wrong?
As you can see I explicitly defined which part of User class I'm calling for because IntelliSense didn't suggest me my extra method.
When you call a method from a class, there are no “parts” of the class anymore.
If you need to (and can) specify the full namespace of the class to invoke a method from it that means you actually have two different classes in two different namespaces. If the two partial declarations are in different namespaces, then you have actually declared two separate classes, not a single class from two parts.
I have a number of classes in a Classes file, and I want them all to be able to access the same, global method to save duplicating code. Problem is, I can't seem to access a method from another class in my file - any ideas?
So my class1.cs layout is similar to this:
public class Job1
{
public Job1()
{
}
}
public class Methods
{
public static void Method1()
{
//Want to access method here from Job1
}
}
You'll need to specify the class they are in. Like this:
public Job1()
{
Methods.Method1()
}
If the class Job1 is in a different namespace from Methods then you'll need to either add a using clause, or specify the the namespace when calling the method. Name.Space.Methods.Method1()
Actually. Public Job1(){} is a constructor and not a method. It can be called from main class by creating object form the JOB1 class. Here add the following code:
public static void method1()
{
Job1 j1=new Job1();
}
constructor can be invoked by creating a object to the corressponding class....
To access methods of other classes, the methods must be static with a public Access modifier.
static - Not bound to an instance of the class but shared by all other instances.
private - data can only be accessed from inside the same class.
public - data can be accessed from other classes but must be referenced.