Override dll class property set - c#

I'm using a thousand instances of a closed DllClass in my project.
public sealed class DllClass
{
public DllClass();
public string DllClassProperty {get; set;}
}
DllClassProperty set is used a thousand of times and I need to override the value set if a parameter is set on Web.config.
I found this Interface INotifyPropertyChanged, but I can't use it, because I don't have access to the class and I can't extend it.
I'm thinking, if there's a way to do something like this, but I think this is not possible in C#:
public class OnSetPropertyListener<DllClass>
{
public void OnSetProperty(PropertyInfo propertyInfo, DllClass instance)
{
// set another value, for example: "new value"
}
}
How can I override the value set in DllClassProperty? Is it possible?

Surprisingly, there is a way to solve your problem. It's not pretty, but it satisfies the constraints of your question.
Step 1: Create a wrapper around DllClass, i.e. a new class MyDllClassWrapper, which behaves exactly like DllClass except for the change that you want to implement. This is usually done by rebuilding the public interface of DllClass and just forwarding all operations to a private DllClass instance.
Now you just need to use MyDllClassWrapper everywhere where you currently use DllClass. You mentioned in the comments that you don't want to change all those calls, so let's automate that:
Step 2: Use Substitute.Fody to automatically replace all references to DllClass by references to MyDllClassWrapper in a post-compile step:
[assembly: Substitute(typeof(DllClass), typeof(MyDllClassWrapper))]
Note, though, that everyone reading your code will be thoroughly confused, since the source code points to DllClass, but MyDllClassWrapper is used instead. Thus, I recommend that you use this technique only as a temporary workaround until you find the time to cleanly replace all references to DllClass with references to MyDllClassWrapper.

Related

C#: Force constructor signature using abstract class?

I've been searching for a while on this because I'm naturally forgetful and I thought it would be nice to build something (an abstract class, interface, etc.?) that would force me to implement certain bits of code in a class I was writing.
In particular, I would like to force a new class to always have a constructor that takes a single parameter typed as itself in order to make duplication of the object easier. I've seen articles/questions elsewhere that talk about this, but I'm not sure this particular question has been asked (at least that I can find) or I'm simply not understanding enough of the other articles/questions to realize it. My apologies in advance.
I'm not interested in having a constructor in an abstract class, interface, etc. actually do anything. I'm merely interested in defining the requirement for a constructor signature in a derived class.
My ideal class would look like this:
public class GoodClass
{
public GoodClass(GoodClass goodClass)
{
// copy components of goodClass to this instance
}
}
So, I first began researching interfaces and also started reading up on abstract classes. I was thinking something like the code below would work, but alas I get errors. Is what I'm trying to do even possible? Is there any other way I could accomplish my goal without putting a sticky note on my monitor? :)
abstract class SelfConstructor
{
abstract public SelfConstructor(SelfConstructor) { }
}
class NewClass : SelfConstructor
{
//Required by SelfConstructor:
public NewClass(NewClass newClass)
{
// copy components of newClass to this instance
}
}
You could write a ReSharper plugin that recognises this case and highlights the class if it doesn't have a "copy constructor". This would be a daemon stage that would process the file as it's being edited, and add highlights. You can look through the abstract syntax tree of the file, look for all instances of IConstructorDeclaration, and then get the constructor's parameters from the ParameterDeclarations property. You can check that there is a constructor that only has one parameter, and that parameter is the same type as the class it's declared in.
You can compare the types by getting the constructor's parameter's TypeUsage and trying to downcast to IUserTypeUsage. You can then use ScalarTypeName.Reference.Resolve() to get an instance of IDeclaredElement. Compare this against the class's IClassDeclaration.DeclaredElement to see if they're the same instance.
In C++, what you are talking about is a copy constructor, you actually get one by default!
C# doesn't have that concept (though of course you can define one); however, it is easier (and preferred) to simply implement ICloneable (MSDN), which requires you to implement the Clone method, that does the same thing.
Instead of:
object myObj = new CloneableObject(otherObj);
You write:
object myObj = otherObj.Clone();
The other thing you could do is force a constructor signature by not having a default:
public class BaseClass
{
//No abstract constructors!
public BaseClass(BaseClass copy)
{
}
}
Now when you derive, you have to use that overload in the constructor. Nothing will force the derived signature, but at least you have to explicitly use it:
public class DerivedClass : BaseClass
{
public DerivedClass() : base(this)
{
}
}
The above example clearly shows that it doesn't "force" you to have a copy constructor, but like a sticky note, would serve as a good reminder.
I would definitely go the interface route, as that is what is there for (and you can use an abstract implementation!).
Note that you can take advantage of Object.MemberwiseClone if you want a shallow copy for free. All objects get this, no interface required.

making an object accessible to child instances only

i have the following class
public class Manager
{
public SharedObject sharedobj {get;set;}
public SomeObject someobj {get;set;}
public AnotherObject anotherobj {get;set;}
//...
}
i want sharedobj to be only accessible from any instance that is in the Manager class instance
making it static is not an option since i will have multiple instances of the Manager class, so the only thing in my mind is sending the sharedobj to the constructors of each object that will use it, i was wondering if there is a better way to achive such thing without having to reference the sharedobj in each instance that will need to use it.
another way i thought of is using the protected keyword and make the other classes inherit the manager
protected (C# Reference):
The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers, see Accessibility Levels.
This is assuming you want each to have his own shared object that you can access if you have the manager.
On a side note, you could also use Dependency Injection (a.k.a DI) to do it. Here's the easiest, shortest explanation of DI I've seen so far: http://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html .
It's a bit more advanced approach with it's own positives and negatives like everything else, but at least read the short link I've mentioned so you'll have an idea of what it is.
You will have to pass it to each object, just as you wrote. Either in the constructor or simply make a setter in SomeObject and AnotherObject, and use that. I would go with what you wrote, and pass it through the constructors.
On a sidenote, if nothing else but the objects within Manager should use SharedObject, then it probably should be private instead of public in the Manager class.

How to force a C# class to have a constant value in it? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to force a C# class to implement certain static functions?
Consider a class and consider that, for some reasons, you need to force this class to have a constant inside it. This is to be applied to a whatever set of classes. In my specific case I need some classes of mine to have a constant inside them to hold the corresponding null value.
Those classes that, in my case, implement a certain interface because they must behave in a certain way, must also have three special values that are needed in my context (context that is too long to explain and quite useless here).
So basically I need a way to force my classes to have a certain constant inside them (accessible from outside). I know that I could simply put the constant in those classes, but what if I am looking for a way to tell the compiler: "If this class implements this interface (for example), that you should not compile it if there is not that constant!".
In this way there is the compiler checking, and not just the programmer who might forget to put the constant.
I hope I could explain my problem. Thanks in advance.
So basically I need a way to force my classes to have a certain
constant inside them (accessible from outside). I know that I could
simply put the constant in those classes, but what if I am looking for
a way to tell the compiler: "If this class implements this interface
(for example), that you should not compile it if there is not that
constant!".
You can achieve something like this creating a class containing an unique public constructor which requires all the information/values you need.
So for example you could use something like:
class myClass{
public readonly int Value1;
public readonly string Value2;
public myClass(int value1, string value2){
Value1 = value1;
Value2 = value2;
}
}
Infact in this case the programmer is forced to instantiate the object giving the right values to the unique constructor available, and can't change the value of the two public fields (due to the readonly keyword).
Explanation from a previous question on the same topic:
A call to a static method is done through the class name, not through
an object reference, and the IL code to call it will call the abstract
method through the name of the class that defined it, not necessarily
the name of the class you used.
Previous post: Why can't I have abstract static methods in C#?
What is wrong with just adding the static method into the class? I don't see why you need another layer when its perfectly logical to code in the static method directly into the class.
public class MyClass {
public static MyClass TheMethod(int i){
// TODO:
}
}

C# share code between classes

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

C# class separation into a header and a .cs file

Is there a way to separate a C# class into a header that contains the class definition and then an actual .cs file that contains the implementation? I suppose one can do this by creating an interface, but that doesn't seem right. I just want a file where I can just see the class design, and not all the detail. It's easy enough to do in C++, but I haven't seen it done with C#.
Thanks in advance.
That's a wrong approach. C# isn't C++. Forget about header files.
If you want the class summary, just open the Object Browser in Visual Studio. It will give you the signature of all the methods within your classes.
You could use partial classes and partial methods. I'm not sure why you'd do this though...
Partial Classes and Methods - MSDN
In the same file, you can use Visual Studio outline function to collapse the class so that you only see the names of methods and properties.
You can also use Visual Studio to see the Class View which gives you the names of various methods and properties of a class.
There is almost no reason in dotnet to need to define a class in a separate place from its implementation.
No there is no way (or real reason) to want to do this in C#. You can get VS.NET to summarise a class for you (collapse all in the view menu) or if you really want to as you say you can use an interface. What is the reason behind you asking?
I don't think you can do header files like you can in C++.
Check out the partial keyword for both classes and methods. I just learned about them yesterday, so I haven't really used them, but they might help you accomplish what you're trying to do.
Extracting the interfaces isn't a great plan if you're interested in the private methods.
Using abstract classes means materially altering the design of the application (and I think, increasing complexity needlessly) to support the "view" requirement. Partial classes don't show you the complete public and private signature in one place, so that's not ideal either.
So if you don't have the IDE, or don't want to use it, I would use the default disassemble action in Reflector (free, and a great toy to have anyway):
http://www.red-gate.com/products/reflector/index.htm
eg. System.Web.Caching.Cache
public sealed class Cache : IEnumerable
{
// Fields
private CacheInternal _cacheInternal;
public static readonly DateTime NoAbsoluteExpiration;
public static readonly TimeSpan NoSlidingExpiration;
// Methods
static Cache();
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public Cache();
internal Cache(int dummy);
public object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Get(string key);
internal object Get(string key, CacheGetOptions getOptions);
public IDictionaryEnumerator GetEnumerator();
public void Insert(string key, object value);
public void Insert(string key, object value, CacheDependency dependencies);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Remove(string key);
internal void SetCacheInternal(CacheInternal cacheInternal);
IEnumerator IEnumerable.GetEnumerator();
// Properties
public int Count { get; }
public long EffectivePercentagePhysicalMemoryLimit { get; }
public long EffectivePrivateBytesLimit { get; }
public object this[string key] { get; set; }
}
This was only a feature of C++ because ancient compilers needed a forward-declaration of the function signatures to work properly.
If this is something that you find handy to have though, and you want more than once, you could try writing a small utility that used reflection to extract the public interface from any component, and format it out to a text file in whatever layout you wanted.
Another alternative would be to use the /// syntax to create XML documentation for the class.
You can use an interface to achieve the same intention.
IFoo.cs:
public interface IFoo
{
int DoFoo();
}
Foo.cs:
public class Foo : IFoo
{
public int DoFoo()
{
return 1;
}
}
Isn't this what the IDE is for?
EDIT: Otherwise inferfaces and abstract classes is the way to go.
Try the Class View. When you click on each class you will get the members listed.
The IDE will show you exactly that inline when you have an instance followed by the "." like
myBadlyNamedObject.
(or "ClassName."), and the beauty is that you have it at your fingertips when working with the object and not when you decide to open up the object definition to see what it might be
As far as I know that's not possible. You can however make things a little bit better by using partial classes where you put different parts of a class in different files. You can for example put all public methods in one file and all private in one to make it easier to get an overview of which methods are available for use from other objects.
If you really, really need to do this, then the closest option would be
Refactor --> Extract interface.
To all you people saying "USE THE IDE~!~~", you're missing the point. Code isn't always read in the IDE. Maybe he wants it to be printed out? Or emailed? That's the problem with not implementing language features because you can get the IDE to do it: Code isn't always read (or even written) in an IDE.
That said, you can use partial classes and methods to do it; I don't think you'll be able to have instance variables in both files, however.
WinCV is a .net 1.0 framework sdk utility that gives you a c++ like header view for .net assemblies. Search google for wincv.exe on how to configure it for .net 2.0.
you can always use a partial class

Categories

Resources