I need to hide few methods inside a class based on the parameter that is passed to the constructor in c#. How would I do this?
Thanks in advance!
More Info:
I was part of this GUI development where they had a API with access to registers in a hardware. Now they are releasing a newer hardware so I need to support both old and new one which has a newer API(Mostly duplicate of old one with some old removed and some new registers added).
Moreover, I need to keep this only one class called "API" as we used it in many places. So the idea of using a newer API with a different name was ruled out.
Now finally, I got this idea of including the newer one into old one with just conditionally hiding the registry access methods.
You can't toggle the visibility of members..... the best bet is to have different interfaces that hide the members.
public interface IName
{
string Name { get; set; }
}
public interface INumber
{
string PhoneNumber { get; set; }
}
public class Worker : IName, INumber
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
So either use Worker through the IName or the INumber interface and it will hide the other members on the class....
I think you might be looking at a re-factor here. Try making a base class with all the methods / properties that behave the same regardless of the parameter, then two child classes which behave differently. Also have a look at the class factory pattern.
You will need to restructure the code into multiple classes or interfaces. You can't dynamically change the visibility level of class members based on a parameter value. Members are construction time information not run time.
You can't change visibility of methods, but you can pass parameter to the single method and do some logic depending on your parameter by using switch - case. But it depends on your method structure.
Try to review your class and change its design. Maybe you can find any design pattern that will help you.
You may actually do something alike using Dynamic code generation, although this is more like a hack than actual code that should be used in production.
Maybe if you explain why you need this then you may get more relevant answers.
Related
I've seen a ton of opensource frameworks that implement dynamic programming in C#. Is there one that can generate an implementation of an interface without there being any actual concrete class?
Specifically, suppose you have:
interface IThing {
int Id { get; set; }
string Name { get; set; }
}
And you also have objects you want to map into instances of IThing:
class Foo {
public int FooBarId { get; set; }
public string FooBarName { get; set; }
}
My hypothetical helper would let me write something like:
IThing concreteThing = helper.Implement<IThing, Foo>()
PropertyGetter(x => x.Id).Returns(foo => foo.FooBarId)
PropertyGetter(x => x.Name).Returns(foo => foo.FooBarName);
I suppose in my pretend example it would put exception throwing stubs into the setters of other properties I didn't supply...
I have an opensource framework ImpromptuInterface (in nuget) that given an interface, will generate stubs to DLR calls (recursively even). Which means you can add whatever logic you like behind it with an implementation of DynamicObject.
see this example.By using Reflection, you can avoid having to specify every possible Type within the implementation, but then you have other drawbacks:
The owner parameter do not expose any Type-information that is expected by the function. You need to check them manually.
Reflection overhead degrades performance on each call.
Reflection degrades maintainability (the method has to be implemented different).
Some operations (like Indexers) are tricky to handle with Reflection.In statically typed languages like C#, the interface of a class defines which operations are supported. A supported operation may be calling a method with a specified signature, or getting or setting a property, or be able to attach to a specific event. In most cases, this makes perfect sense, since the compiler is able to verify if the operations are supported by the specified type.
So I've (mostly) wrapped my head around C#'s componentization paradigm and why that's a superior (more predictable, flexible) alternative to confusing and quasi-unpredictable multiple inheritance of c++.
However, I have a couple things that are trouble me.
So if I understand correctly the general approach to adding a component is:
Create an interface that has that component of name I<ClassName adjective>
public interface IHasGear { Gear gear { get; set; } }
public interface IBladeEquipped { Blade blade { get; set; } }
Create an extension class that calls appropriate methods in the interfaced classes.
public static class GearExtensions
{
public static void Stop(this IHasGear machine)
{
machine.gear.KineticStop();
}
public static void Accelerate(this IHasGear machine)
{
machine.gear.ApplyAngularAcceleration();
}
}
public static class BladeExtensions
{
public static void Cut(this IBladeEquipped machine)
{
machine.blade.Cut();
}
public static void ReSharpen(this IBladeEquippeded machine)
{
machine.blade.ReSharpen();
}
}
And then finally add the interface reference and instance of the referenced class to my class that uses the selected component.
public class MeatGrinder : IHasGear, IHasBlade
{
public Gear oldToothyOne { get; set; }
public Blade mrPointy { get; set; }
public MeatGrinder() { oldToothyOne = new Gear(); mrPointy = new Blade();}
}
Now my couple of questions:
Why ALWAYS force the instantiation of the var?
I understand that you might want this if there is inheritance, as you could implement the var with different children. But what about the simplest case of non-inheritance? Why not build in an automatic mechanism to auto-implement in the compiled code the base class(es) in the interfaces is (are) implemented if they are not explicitly implemented
Is there a way to template this process in a ubiquitous fashion?
Obviously this is a repetitive task, if you have several components. Given the ambiguity, is there a way to streamline the workload??
Is there a superior componentization(/inheritance) scheme to the method I describe?
Things to keep in mind:
There's only a few component classes.
I want to be able to use the component class functions as direct calls in the composited class.
There are multiple composited classes (component classes << composited classes)
The components are dissimilar and thus not appropriate for unification in one class.
Given the above considerations an approach that forces me to write individualized code for each composited class is not a desirable approach.
EDIT 1:
I shouldn't have been ambiguous. The reason why I'm not using direct inheritance here is because I have multiple "key" components with functionality that I want to be able to directly address ubiquitously and publicly... e.g. I want to be able to say:
Machine myMachine = new Machine();
myMachine.Accelerate();
myMachine.Cut();
myMachine.ReSharpen();
Hopefully that helps to clarify my question and why I'm adopting this scheme.
Also, I had a couple errors in my example code (a var was non-public and my naming was consistent... these have been corrected.
EDIT 2:
Things that don't make sense for me (to my understanding):
a) Abstract Classes
Why? No multiple inheritance
b) Implicit Operators, a la, hcb's suggestion:
http://www.codeproject.com/Articles/10072/Simulated-Multiple-Inheritance-Pattern-for-C
Why? This approach requires you to create operators for ever class utilizing the component classes, which would result in much more code in a scheme where the interface is commonly used. To me if you're going to go that route, just make traditional wrapper functions rather than get all fancy.
My need for a more elegant solution is driven by ubiquity and mass use of a couple common components that perform redundant functionality, but are dissimilar and thus inappropriate to lump in a single class (despite the convenience that would provide).
Edit 3:
Props to svick for showing me how to format my code nicely without edit diving! :)
Retitled the question to make it more clear, added more precise requirements for suggesting alternate solutions.
What you're doing is just an attempt to emulate multiple inheritance. I don't think it's “the general approach to adding a component”.
I don't think what you're doing is a good way of using extension methods, it looks more like an anti-pattern to me. Especially since you're doing it just to save a few keystrokes, it doesn't add you any other benefit.
I think the answer to your questions about why you can't use some simpler way to do that is that C# tries to be explicit and consistent.
Explicit in that it won't guess what you mean, it makes you spell it out. This is because its guess could be very easily wrong. And the rules how exactly does it guess would probably have to be very complicated and thus confusing. (“I made this little change and now my code behaves completely differently.”)
Another thing is consistency: if you usually implement interface one way, but sometimes you do it differently, it makes the language more complicated and more confusing. Of course, there are cases where inconsistencies like this are worth it.
Specifically, if the feature of automatic implementation of properties from interfaces would work, your code would compile, but wouldn't work correctly: IBladeEquipped defines the property blade, but your class contains the property mrPointy. The compiler would see that you don't implement the required property and implement it for you. And then your code would fail with a NullReferenceException, because blade will always be null. So I think your code presents a good argument against that feature.
Also, I think your example is actually quite good at explaining why you shouldn't write the code the way you want. If you want to resharpen the knife of a meat grinder, do that: grinder.blade.Resharpen(). Writing it differently would feel less natural and more confusing to me.
I'm not sure if this is what your looking for but i like to couple interfaces with abstract base classes to implement default methods and properties:
public interface IHasGear { Gear gear { get; set; } }
public abstract class BHasGear : IHasGear { public virtual Gear gear { get; set; } }
public class MeatGrinder : BHasGear
{
//no need to implement gear, the abstract class already implemented it
private Gear oldToothyOne { get; set; } }
}
I have been coding classes like this:
public class ReportViewModel
{
public string Status;
public string DataSource;
public String DataStore { get; set; }
public PageMeta PageMeta { get; set; }
public ICollection<Question> List { get; set; }
}
Note that most of the fields use { get; set; } except the first two which I let Visual Studio add for me.
What I am wondering is do I really need to use { get; set; }. It seems to me that VS2010 does not automatically add this so do I need it?
You've created a class with two public fields (Status and DataSource) and three public properties (DataStore, PageMeta and List). I would advise against having public fields - and you should actually consider whether you really need all of these to be mutable properties at all.
There are various advantages to using properties over public fields, but the main one in my mind is that a property is logically part of the API of a class, whereas a field is logically an implementation detail. The property says what callers can do - a field says how a value is stored.
{ get; set; } indicate autoimplemented properties. In .NET there is a difference between properties and fields. Normally fields should be private. They are used for some specific implementation and should in most cases be internal to the class. Properties on the other hand are used to encapsulate behavior that is exposed to the consumers.
If you want them properly exposed as properties, yes.
They are different: your first two members are fields - not properties. The others are properties with auto-implemented accessors.
When you don't add the get and set you are using a field rather than a property. Which in many cases won't make a lot of difference. However, you can't databind to a field like you can with a Property. So you would lose that.
At all depends on how this class will be used.
If this is in your code, just used in your current product, then there isn't really much difference between fields (no {get;set;}) and properties (with the {get;set;}).
However in that case they probably shouldn't be public, make them internal or private instead so that it's clear that external code shouldn't use them.
If your class is going to be used by other assemblies then you should always convert public fields to properties.
The reason is that if you want to extend properties later on (i.e. add a body to the set) then your users can just get the new DLL from you. However if you've used fields then converting them to a property will look the same in the IDE, but require your users to recompile when they get the altered DLL.
Being public tells consumers that they can rely on that member being present, being a property gives you more control of how you deliver it to them.
There is a difference. The first two are fields and the remainder are auto-properties.
The second one, the compiler generates a private backing field and some boiler-plate get/set methods. These then allow you to access the properties like they were fields, but with the advantages only available to properties.
It is always recommended to hide fields behind properties, by either making them private and writing your own property around it or using an auto-property.
There's some advantages to properties. One being that properties can be made read-only, or even write-only, or read-only with an internal write-only, etc. Since they act just like methods, you can execute any arbitrary code inside of them. This is useful for when you need to implement things like INotifyPropertyChanged or if the property is actually calculated from several fields behind it.
The other advantage is encapsulation. You aren't tying yourself directly to the fields of the class, but rather the property. So if some detail about the field changes (say it goes away and becomes calculated), by using the property you are insulating yourself from those implementation details.
You should certainly look at using properties (for now adding the { get; set; }) for all cases. They are good practice in that they provide a level of encapsulation that shields the user from implementation specific details.
You do not have to, but this just coding stundart, with its pros and cons.
Consider this link for more resources:
Property Acessors
In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda
I'm working on building my own base user interface classes. On them, I want them to all have similar "common" properties and methods. I could define an interface class, but interface appears to only allow abstract methods, and no properties.
I don't want to copy the otherwise exact same code to each class, but not sure how to implement... Ex: I want this common stuff to be applicable to Buttons, Textbox, Checkbox, Listbox, etc user controls.
Suggestions???
In this situation I usually use abstract classes. Create your base abstract class and then inherit it from your new controls.
I myself come from a C++-background where multi-inheritance is allowed and used extensibly, so I often ran into the same problems as you.
The first thing you need to do is to read up on mix-ins - here you'll prolly notice that you've used them yourself all along, without ever naming them.
Second step is to start to recognize your mixins whenever you need them, and you'll often find out that you might as well use them via composition.
Third step is to implement them using composition... Yes, i hate this too, but there's no way around it if you wanna go .NET (or Java or...) :)
What you should use inheritence for is not for your mixins, but for stuff that actually identifies your items. I recommend looking at the .NET hierachy for some of the common controls (textbox and the likes) to get some inspiration.
Good luck
You can define properties on interfaces: interface properties
public interface ISampleInterface
{
// Property declaration:
string Name
{
get;
set;
}
}
You can declare a property in an interface as below:
public interface IMyInterface
{
string Name { get; set; }
int Age { get; set; }
}
However, in this situation it sounds like an abstract class would be better.
It's definitely possible to specify a property on an interface
interface IFoo {
string Name { get; set; }
string Age { get; } // Read Only
}
But otherwise you are correct. Interfaces specify no behavior and hence can only define "abstract" methods and properties. The implementation must be done on every single implementor. That's the price that is paid for flexibility in interfaces.
If the behavior is truly identical between all of the child classes then I usually go for an abstract class. Or often a combination. Namely define an interface and a base implementation which implements that interface.
class Foo : IFoo {
private string _name;
public Name { get { return _name; } set { _name = value; } }
public Age { get { return 42; } }
}
This allows you the flexibility of a quick implementation with the choice of usincg an interface for classes that for some reason cannot derive from Foo.
.Net doesn't allow multiple inheritance, but you can use an "inheritance hierarchy" to organize your base classes. This is how .Net itself is laid out.