Find usages of a generic class with specific constraint - c#

As per title, how can I find usages of the method Process for Processor<int> rather than Processor<string>?
internal class Program
{
private static void Main()
{
var processorInt = new Processor<int>();
var processorString = new Processor<string>();
processorInt.Process();
processorString.Process();
}
}
internal class Processor<T>
{
public void Process() => Console.WriteLine(typeof(T).Name);
}

ReSharper can handle this out of the box. If you try to perform a search for references, it'll actually ask you what you want to look for. Just declare a dummy variable of the type you want to look for, and call Find Usages, on the type name.
Note that this works for generic classes and generic methods, but it won't help you if you're looking for usages of a method in a generic class with a given type parameter.
Or just use Right click -> Find usages advanced:

You can't using standard tools.
You either have to:
Press Ctrl+K, Ctrl+R to find all references to Processor<T>.
Visually filter on Processor<int> yourself.
Or:
Find all using text search on Processor<int>. This is not very useful when you have SomeOtherProcessor<int> too, since that would match too.
This are the only options I have come up with. Other developer tools, like Resharper, might have an option that is better.

I fear the only way to achieve this is by directly searching for Processor<int>() within the search-and-replace-tool. Quite annoying though. However this won´t help ypu much if your generic class has a generic interface-parameter instead of a struct or class. Thus you cannot search for usages of Processor<MyInterface>() when you are interested on occurences of all Processor with a generic parameter of that interface.

You can use my tool built with Roslyn APIs:
https://github.com/UnoSD/SubTypeReferencesAnalysis

Related

Extending Simple.Data with assertions

I'm using this very nice mini ORM, Simple.Data, to setup a lot of test data, quick and easy.
I would really like to extend it for assertions. For example i would like to assert on count:
Db.MyTable.GetCount(); <- Returns a dynamic
So that I could evaluate more or less like you would do with FluentAssertions.
It could look like this:
Db.MyTable.GetCount().ShouldBe(X);
But I'm finding it very hard to do this without loosing the advantage of dynamics.
Does anyone have a hint of how this could be done or if its even possible within reason?
I'm currently traversing the src at GitHub trying to find a way i can do this locally and toying around with impromptu to find a way.
Sadly, there is no happy answer to this. Dynamic and extension methods do not mix, as explained by Jon S and Eric L here: Extension method and dynamic object
The answer, as in that question, is either to invoke ShouldBe as a static method:
AssertionExtensions.ShouldBe(Db.MyTable.GetCount(), 3);
or to inline-cast the method's return value to the known type:
((int)Db.MyTable.GetCount()).ShouldBe(3);
Or, as you are investigating, to use Impromptu to apply an interface to MyTable with a GetCount method. I'm guessing you've seen my blog post on Simple.Data and Impromptu, but if you haven't: http://blog.markrendle.net/2012/10/12/howto-dial-up-the-static-on-simple-data/
In the classes you are creating why dont you create your own custom assertion class and make the object classes you are creating inherit from them.
public class MyClass : MyCustomExceptionClass
{
}
In that way it would be easier for you to test the methods in the way you want

Find usage of a particular method when called with a particular subtype

I'm refactoring the nasty out of a largeish codebase and need to find where a particular method, accepting instances of a fairly general interface, is called with a particular implementation of that interface.
For example, in the NastyStatic is the DoBadThings(IBusinessObject) method. I have about 50 classes that implement IBusinessObject in my business library, including DontHurtMe : IBusinessObject.
How can I find every call to NastyStatic.DoBadThings(foo), but only where foo is an instance of DontHurtMe?
EDIT: I'm after some sort of static analysis tool. Setting a dynamic watch in DoBadThings (or similar) and running the application isn't really an option. It will already throw an exception due to changes I've made to DontHurtMe, and there are far too many code paths to find all usages that way (at least until it goes live and my users start complaining).
Easy. Write an overload of DoBadThings that takes a DontHurtMe as a parameter. Now see where it's called. This won't detect the cases where the method is called with a declared IBusinessObject that happens to be a DontHurtMe - but I don't think static analysis can detect that. This gets all the calls of your method with a declared DontHurtMe.
ReSharper 5's Structural Search can do this. Supposing the following code:
class Program
{
static void Main(string[] args)
{
var hm = new HurtMe();
var dhm = new DontHurtMe();
DoBadThings(hm);
DoBadThings(dhm);
}
static void DoBadThings(IBusinessObject ibo) { }
}
interface IBusinessObject { }
class DontHurtMe : IBusinessObject { }
class HurtMe : IBusinessObject { }
Now, as noted, a R# Find Usages on DoBadThings, no matter what options we specify, will find both the invocations in Main.
But if we
Go to ReSharper | Find | Search with Pattern....
Add Placeholder | Expression, name it dhm and specify DontHurtMe as the type
In Search pattern, type DoBadThings($dbm$)
Click Find
we get in our results only the invocation of DoBadThings on the object with type statically identifiable as a DontHurtMe, and not the invocation on a HurtMe.
I do like the neatness of the procedure offered by #Carl Manaster, but this way gives an option for when you can't overload the method in question.
I can't come up with solution for static analysis. I just re-examined the options of ReSharper's "Find usages advanced..." and didn't find anything. You could put a condition breakpoint on this method with a condition like foo is DontHurtMe, but I suppose you know that already and it's better suited for the cases when you try to locate a bug than for refactoring purposes.

Appropriate use of Static Method

Conceptually, is it appropriate to use a static method (C#) when the method will only take inputs and reformat the input as the output? For example:
public static string FormatString(string inputString){
return "some formatting" + inputString + "Some other formatting";
}
If I were to have a few of these types of methods, would a static "utility" class be a good idea?
I'd agree with the other answers so far that it certainly makes sense a lot of the time.
Sometimes, you may want to actually give yourself a little more flexibility by defining an interface and implementing that with instance methods. This gives you the option of using different methods in your code down the road.
Here's an example of what I mean. Say you are using this formatString method of yours in some code somewhere that looks like this:
public void DumpToConsole()
{
foreach (DataField field in m_fields)
{
Console.WriteLine(StringUtils.formatString(field.ToString()));
}
}
OK, this is great. (Actually, it's stupid, but whatever—for illustration only!) But you could make such a method more flexible by having it accept an interface, of which you might have various implementations which provide completely different sorts of formatting:
public void DumpToConsole(IFormatter<DataField> formatter = null)
{
// Perhaps you could specify a default. Up to you.
formatter = formatter ?? Formatter<DataField>.Default;
foreach (DataField field in m_fields)
{
Console.WriteLine(formatter.Format(field));
}
}
Then instead of StringUtils being a static utility class, it would be merely one implementation of a class that offers a way to format a certain type of object (in your case, string objects; in my example, these imaginary DataField objects).
So this is all a very long-winded way of saying, it depends. If you're aiming for super flexibility down the road, maybe you should consider implementing an interface instead of going with a static helper class.
Do note that in my example above, another completely acceptable way of approaching the problem could've been to accept a Func<T, string> delegate instead of this hypothetical IFormatter<T> interface. This is mostly a stylistic choice, in my opinion. But often interfaces become more realistic when there are multiple behaviors that you want to customize; i.e., defining methods that accept 3, 4, or more delegates can quickly become cumbersome compared to accepting a single interface.
Yes, if you have several static methods that are generally related, putting them together in a static utility class is a good idea.
If you're talking about convention, it's also worth noting that naming conventions in most .NET code call for Pascal-cased public members (so FormatString instead of formatString) and camel-cased parameters and fields (so inputString instead of InputString).
If you're making these public, then yes, it might potentially be better to make a utility class of some sort.
That being said, I would try to make it as "general purpose" as possible, since otherwise, they tend to get unmaintainable quickly.
Yes, the static methods in the way you are using them in C# is very similar to C++'s idea of "free functions". It just so happens C# doesn't have free functions. Eric Lippert has an interesting post around here somewhere of why that is the case. A static class is used to group functions of similar utility and would be appropriate if you had several of these that were similar.
Yes that's fine, your class will then act as a 'library' of related functions. Your other choices for this would be to either pollute the global namespace with various functions or to create a Singleton which would be unneeded since there's no 'state' to account for...
Yes, you could do that. Or you could create a string extension method.
msdn extension methods
For your example above, I would use the string formatter instead of inline concatenation.
string.Format("some formatting {0} some other formatting", inputString )
It is if that particular formatting would be useful in more than one place in your code.
If it would make sense only within one specific class, then I'd rather use a private method (static or instance, it wouldn't make a difference).
Utility classes are a useful thing. The only thing you should be careful about is not to use them too often. If most of your code is in utility classes, then you're doing something wrong. But factoring out some common code in helper methods is a perfectly justified use.
You could use an extension method for this to extend the String class. It would make the calling code a little neater, but it's just a matter of personal taste in the end.
public static string MyWeirdFormat(this string str)
{
return string.Format("{0} is weird",str);
}
public static void Test()
{
string myString = "ABCD";
string weirdString = myString.MyWeirdFormat();
}
In my opinion the answer is yes you would put these methods in a Utility (Util) class. On a Java web-based application that I am currently working on we actually have 3 such Util classes each of which comprises of only static methods similar to the one you have shown. The reason why we have 3 is one for the client only Util methods, one for server only and a third one for shared Util methods.
Depending on what your app is you may end up with something similar.
As an aside, if you want to learn more about when to use static classes in C#, have a look here.
I hope that answered your question sufficiently.
Personally I'd lean more towards the use of an extension method, still static though ;)
public static class StringExtensions
{
public static string MyFormat(this string input)
{
return string.Format("some formatting {0} Some other formatting", input);
}
}

Advice on C# Expression Trees

I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.
The basic idea is that this method will add certain things to a collection that will be used for validation.
public interface ITestInterface
{
//Specify stuff here.
}
private static void DoSomething<T>(Expression<Func<T, object>> expression, params IMyInterface[] rule)
{
// Stuff is done here.
}
The method is called as follows:
class TestClass
{
public int MyProperty { get; set; }
}
class OtherTestClass : ITestInterface
{
// Blah Blah Blah.
}
static void Main(string[] args)
{
DoSomething<TestClass>(t => t.MyProperty,
new OtherTestClass());
}
I'm doing it this way because I'd like for the property names that are passed in to be strong typed.
A couple of things I'm struggling with..
Within DoSomething, I'd like to get a PropertyInfo type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from "Convert.([propertyname])" and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way?
Is this a specific pattern I'm using?
Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.
Thanks!
Ian
Edit:
An example of what expression.Body.ToString() returns within the DoSomething method is a string that contains "Convert(t.MyProperty)" if called from the example above.
I do need it to be strongly typed, so it will not compile if I change a property name.
Thanks for the suggestions!
I rely heavily on expression trees to push a lot of what I want to do with my current application to compile-time, i.e. static type checking.
I traverse expression trees to translate them into something else which "makes sense".
One thing I've ended up doing a lot is that instead of URLs I rely on a MVC like approach where I declare lambda functions, and translates that... interpret, the compiler generated expression tree into an URL. When this URL is invoked, I do the opposite. This way, I have what I call compile-time checks for broken links and this works great with refactoring and overloads as well. I think it's cool to think about using expression trees in this way.
You might wanna check out the visitor pattern, it's a pain to get started with because it doesn't make much sense in the beginning but it ties everything together and it's a very formal way to solve type checking in compiler construction. You could do the same, but instead of type checking emit what ever you need.
Something which I'm currently pounding my head against is the ability to build a simple framework for translating (or actually I should say interpret) expression tress and emit JavaScript. The idea is that the compiler generated expression trees will translate into valid JavaScript which interfaces with some object model.
What's exciting about this is the way the compiler is always able to tell me when I go wrong and sure the end result is just a bunch of strings but the important part is how these strings got created. They went through some verification and that means something.
Once you get that going there is little you can't do with expression trees.
While working with the System.Reflection.Emit stuff I found myself using expression trees to create a light-weight framework for dynamic compilation, which at compile time could basically say if my dynamically created assemblies would compile as well, and this worked seamlessly with reflection and static type checking. It took this further and further and ended up with something which in the end saved a lot of time and proved to be very agile and robust.
So I love this kind of stuff, and this is what meta programming is all about, writing programs in your programs that do programs. I say keep it coming!
Collecting PropertyInfo objects from Expression.Body seems similar to my solution to another question.
I appreciate what you are trying to do with the property here. I have run into this conundrum. It always feels weird to write:
DoSomething("MyProperty", new OtherClass());
If the property ever changes name, or the text is mistyped in the call, then there will be a problem. What I have come to learn is that this is something you probably have to deal with via testing. Specifically, unit testing. I would write unit tests to enforce that the "DoSomething" calls work correctly.
The other thing you might try is to decorate your properties with attributes, and then reflect against your class when it is constructed looking for properties with the attribute, and load rules.
[DoSomething(typeof(OtherClass), typeof(OtherClass2))]
public int MyProperty
{
get;
set;
}
In this case the constructor (perhaps in a base class?) would dynamically create an OtherClass object and a OtherClass2 object, and load them into a collection along with the name of the property.

C# Extension Methods Architecture Question

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();
?

Categories

Resources