I have a method which accesses many fields, so it’s hard coded into its class. I would like to make it reusable by other classes.
Is there any way of getting a list of all fields and methods (within the same class) that a method accesses?
I’m using VS2010.
Sure, take that method out of the class and put it into an empty class and try to compile. Compiler will complain about a list of fields that this method wants to access but could not find.
The Reflection namespace can do just about anything you'd need in this regard. Specifically, I think you'll want to check out System.Reflection.PropertyInfo and System.Reflection.MemberInfo.
Related
I am making the following call to an extension method:
database.ExecuteScalar(command).NoNull<string>(string.Empty);
I get an error that the extension method is ambiguous .
I have two dlls with the same code that implement NoNull(string str) under different namespaces.
How can I explicitly refer to one namespace?
How would I have it done if it was the same namespace?
Update: I cannot rewrite the 3rd party dlls.
Remove the ambiguity by redefining or eliminating one of the methods at the source. You don't need redundancy.
If you do not control the source, include only one of them in your class file via the using directive.
If you still need both namespaces in the given class file, invoke the version you wish simply as a static class call, unambiguously identifying the method via the (potentially fully qualified) class name.
Abc.Xyz.ExtensionsClass.NoNull(database.ExecuteScalar(), string.Empty);
// <Abc.Xyz.> is only necessary if the classes themselves match names
// if not, only <ClassName>.<MethodName> is needed
Just in case somebody will need this...
Ambiguity can be resolved if concurrent namespaces which have extension methods with same name, are included at different levels (most inner included namespace will have priority).
For example:
using Namespace1;
namespace MyApplication
{
using Namespace2;
...
db.Execute(); // Namespace2 Execute() will be called
}
I would strongly suggest that you rename one of the extension methods. Depending on what else you do, you could possibly just remove the using directive for one of those namespaces, but that won't help if you need both namespaces for other things. (This leads to a suggestion to put extension methods in their own namespace, of course.) Renaming is likely to simplify things in general though.
You should change the signature of one (or both of them) to differentiate what it does. This seems like duplication of code somewhere unless these do different things. Though if they do different things I would think you would differentiate that in the names. I'd recommend creating some sort of enumeration (a flag maybe) to pass as an extra argument to one of the methods.
In my case the problem was, that both extension methods had the same namespace like Some.Namespace.Extensions, that i didn't have control over and thus couldn't change.
They were each located in a separate class, though. So I solved it by writing
using static Some.Namespace.Extensions.HostExtensions
instead of
using Some.Namespace.Extensions as using a using statement with a static class is not possible.
In C# is there a way to declare the class then define it later? I really like in C++ where I can list all the methods at the top like a TOC then define everything later.
Can that be done is C#?
I have used the idea of defining a method that just runs a similarly named method in it then the similar method is at the bottom. but I am thinking there is a better way and googling returns a bunch of basic code on creating classes with no answer.
so here is what I do...
...
public void methodA(){methodAcontent()};
public void methodB()...etc...
...further down...
private void methodAcontent(){
...All the code..
}
is there a better way?
this like Interface http://msdn.microsoft.com/en-us/library/87d83y5b.aspx
Or this an Abstract class with abstract methods.
There's not a good way to do this in the C# language, but the Visual Studio IDE can collapse a file to its definitions which you can then expand individually (see this). This along with code regions helps me organize longer files.
Why would you need that?
C# is using multipass compilation, so it doesn't matter where the function is defined and when used. You can have function defined at end of the class and use it in the beginning and it will still compile fine.
Also IDE helps you with that. You have ability to collapse bodies of all methods, there is list of all methods in one combobox and InteliSense is extremly helpful in finding correct methods.
And using practices from C++ in C# is really bad idea, because both are quite different in how they solve the problems.
If you're doing this as a means to "document" the public interface to a class that's properly encapsulating a concept or object in your problem domain, then use an interface.
If you're doing it as a means to get an "overview" the structure of a class, then Visual Studio has several ways to give you this. You can collapse the code to just its definitions (Ctrl+M, O), or look at the Class View (Ctrl+W, C).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.
I am making the following call to an extension method:
database.ExecuteScalar(command).NoNull<string>(string.Empty);
I get an error that the extension method is ambiguous .
I have two dlls with the same code that implement NoNull(string str) under different namespaces.
How can I explicitly refer to one namespace?
How would I have it done if it was the same namespace?
Update: I cannot rewrite the 3rd party dlls.
Remove the ambiguity by redefining or eliminating one of the methods at the source. You don't need redundancy.
If you do not control the source, include only one of them in your class file via the using directive.
If you still need both namespaces in the given class file, invoke the version you wish simply as a static class call, unambiguously identifying the method via the (potentially fully qualified) class name.
Abc.Xyz.ExtensionsClass.NoNull(database.ExecuteScalar(), string.Empty);
// <Abc.Xyz.> is only necessary if the classes themselves match names
// if not, only <ClassName>.<MethodName> is needed
Just in case somebody will need this...
Ambiguity can be resolved if concurrent namespaces which have extension methods with same name, are included at different levels (most inner included namespace will have priority).
For example:
using Namespace1;
namespace MyApplication
{
using Namespace2;
...
db.Execute(); // Namespace2 Execute() will be called
}
I would strongly suggest that you rename one of the extension methods. Depending on what else you do, you could possibly just remove the using directive for one of those namespaces, but that won't help if you need both namespaces for other things. (This leads to a suggestion to put extension methods in their own namespace, of course.) Renaming is likely to simplify things in general though.
You should change the signature of one (or both of them) to differentiate what it does. This seems like duplication of code somewhere unless these do different things. Though if they do different things I would think you would differentiate that in the names. I'd recommend creating some sort of enumeration (a flag maybe) to pass as an extra argument to one of the methods.
In my case the problem was, that both extension methods had the same namespace like Some.Namespace.Extensions, that i didn't have control over and thus couldn't change.
They were each located in a separate class, though. So I solved it by writing
using static Some.Namespace.Extensions.HostExtensions
instead of
using Some.Namespace.Extensions as using a using statement with a static class is not possible.
I recently asked this question:
Compiler error referencing custom C# extension method
Marc Gravell answer was perfect and it solved my problem. But it gave me something to think about...
If and Extension method must be placed on a Static Class and the method itself must be static, why can't we create a static Extension method?
I understand that the parameter marked as "this" will be used to allow access to an instance of the object we are extending. What I do not understand is why can't a method be created to be static... it just seems to me that this is a senseless limitation...
My question is: Why can't we create an extension method that will work as a static Method?
I expect the real answer is simply: there wasn't a good use-case. For instances, the advantage is that it enables a fluent-API over existing types (that don't themselves provide the logic) - i.e.
var foo = data.Where(x=>x.IsActive).OrderBy(x=>x.Price).First();
which enables LINQ:
var foo = (from x in data
where x.IsActive
order by x.Price
select x).First();
With static methods, this simply isn't an issue, so there is no justification; just use the static method on the second type.
As it is, extension methods are not properly object orientated - they are a pragmatic abuse to make life easier at the expense of purity. There was no reason to dilute static methods in the same way.
Because that feature doesn't exist in C#.
As a workaround, static methods can be implemented in another class and called through that class to provide the added functionality.
For example, XNA has a MathHelper class which ideally would have been static extensions to the Math class.
The community is asking if we think it's a good idea for C# 4.0
My thinking would be for compatibility - if you suddenly made all static methods extension methods with the need for the this operator you could inadvertently break code which now is overriding a normal method with an extension method.
The this parameter allows control and thus doesn't break compatibility.
Just an idea though.
First of all you would have to add yet another syntax to indicate you want to extend the static methods of the existing type. When extending syntax you really need a very good reason to do so.
Lets imagine I have a class called MyExts which allow me to add extension methods to MyClass. Why would:-
MyClass.DoSomethingExtra();
be better than
MyExts.DoSomethingExtra();
?