What does the syntax seen when decompiling c# dynamic operations actually mean? - c#

I've recently had to make a forray into decompiling a colleague's code while they're away, and found that most of it looks surprisingly nice (thanks ILSpy), with the notable exception of a couple of places where we needed to use dynamic - these got mangled into several parts:
A call site container - i.e. what resembles a class in definition, but let's say the method in which dynamic was used was DoStuff, would have a declaration along the lines of public /* static? I forget */ class <DoStuff>CallSiteContainer_Plus_Some_Weirdness { /* bunch of CallSite fields */ }
A lot of code that checks whether various CallSites within the container have been assigned and assigns them before usage as required using approaches I really don't get yet.
My question is regarding the syntax of the class declaration in the 1st point. It looks like a generic class, but it clearly isn't. Can anyone explain what's going on there?
Please note, I'm not looking for help in working out the original code - I've already managed to do that by judicious use of find and replace, and breaking out the autogenerated code from everything else. But I'd like to understand how the CallSite container syntax is a valid class name!

Here's an example of such auto-generated class:
private static class <>o__0
{
public static CallSite<Action<CallSite, Type, object>> <>p__0;
}
If you are worried about the <>o__0 class name and the <>p__0 field name, then you are right, those are not valid C# names but this doesn't mean that they are not valid IL names which is what the compiler generates. The reason why it uses such special symbols is to ensure that they will never conflict with class names that you as a developer might have written.

Related

Public Properties instead of PRIVATE fields

First just to clarify and avoid unnecessary duplicate tagging, this question is not a duplicate of this one, neither a duplicate of this other one or others I have already searched. Why? they all talk about public fields or private fields WITH the classical C#'s "properties".
My question is why should I write something like this (Public Properties)
class myClass{
public int AValue{get; set;}
}
when I can write instead (Private fields without any properties involved) (Just classic old C++ style way of writing things)
class myClass{
private int aValue;
public int getValue{ return aValue;}
public void setValue(int value){ aValue=value;}
I am scratching my head, reading many many resources, answers and questions, and no one of them answer this question. They all talk about the advantages over public fiels (which I am not asking about) or about the advantages of the new automatic properties over the old ones (which I am not asking either).
I guess my question is why C# does not use the same way of writing that has worked well in Java or C++ that works well. I don't see any advantage. I would very much appreciate someone teaches me the advantage because afaik is not written anywhere else. (not even in my C# books)
From my understanding the public properties that you are referring to are merely syntactic sugar wrapping the pattern that you describe above.
It comes down to readablity and platform standards I guess. While there is nothing wrong with the way that you are talking about, we also need to consider maintainability. To another .Net developer, that pattern does not fit what they are used to and could cause confusion.
And the there is the superficial reason, it is just a lot more code to write. Especially when you have something like a DTO.
The properties in c# are further encapsulated and eventually translated into an intermediate language of a private field and the corresponding Get Set method, so you don't have to be bothered
Auto-accessors are syntactical sugar for exactly that. The generated code has a backing field and get/set methods. Fields don't have accessors, whereas properties do.
Public/private is about encapsulation/security, i.e. who should be able to access your information.
In the way you presented it (writing get and set method) is good, but you have two methods - one for setting the value of the field and one for getting this value. Using properties, it's more natural to me, since you "encapsulate" set and get method under one name and accessing it is better this way (in my opinion).
The main reason for using public int AValue { get; set; } instead of a private field and a getAValue and setAValue pair of functions is that that's just the way that things are done in C#. From a "what the code does at runtime" perspective, the two are pretty much the same as an "auto property" (the type of property you've got where you let the compiler take care of generating a private backing field) compiles down into code very similar to that which you've written (see this stackoverflow questions accepted answer for an example).
The main "advantage" in the context of your question (why use a property instead of a field and a get/set pair of methods) is predictability and comprehensibility. Anyone who's working with your code will expect to see properties, rather than a private field/get/set implementation and thus your code will be more immediately comprehensible to them. Seeing it implemented differently will cause them to question why, assume that there's a reason for it and thus slow them down when it comes to understanding your code.
C#'s getter and setter is syntactic sugar, which remove noisy method names (SetValue or GetValue vs just Value) and increase readability of the code.
Readability is much better in consuming code
// Without properties
var myClass = new MyClass();
myClass.SetAValue(aValue);
myClass.SetBValue(bValue);
//And with properties
var myClass = new MyClass
{
AValue = aValue,
BValue = bValue
}
Because it is only syntactic sugar - every developer/team are free to not use
it.
Some teams have "rules" that properties should be used only for getting/setting values without any "heavy" logic in getters/setters. And methods should be used for setting or getting values which executes some "heavy" operations.

Decompiling leads to error CS1112, assembly confusion

So I ran a C# university program through de4dot and then reflector to decompile it and the following error appeared when I ran it in VS.
[assembly: System.Runtime.CompilerServices.Extension]
Error CS1112 Do not use
'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this'
keyword
instead. Client C:\Users\user\Desktop\333\as2\decom\AssemblyInfo.cs 15 Active
I tried replacing the code with this and this() among other things but that just causes other problems. Can someone explain what I am to replace with 'this'? I feel like I am missing something obvious here.
The [assembly: Extension] attribute is added to an assembly by the compiler when the assembly contains extension methods. This happens automatically, and based on the error you're seeing, the compiler doesn't want you doing it explicitly. Assuming the rest of the decompiler output is correct, comment out the assembly-level attribute, and you should be fine.
That said, you should never assume that a decompiler's output is correct.
You're meant to add the this modifier to the method:
public static class FooExtensions
{
public static void DoSomething(this Foo foo)
{
...
}
}
That makes it an extension method.
In general thought, I wouldn't try to use a decompiler to "round trip" code - decompilers can be useful to see what the compiler has actually done, but there are various situations where the result won't be compilable.

Constructor with no definition

I'm new to .Net and I just saw this code that doesn't make sense to me (slightly abridged):
namespace test
{
public class sub : super
{
public sub(string text);
}
}
As you can see, there is a constructor that takes an argument, but does not implement a definition. How does that work? My guess is that it somehow relates to the super class, but I dont understand how, and I havent been able to find anything on Google.
Edit: Im running this in VS2010, and I just noticed that the tab has [from metadata] in the title. Perhaps this is why?
That's not code.
That's text that looks somewhat like code based on the metadata in the assembly. You'll see this when the IDE doesn't have access to the source code in question (For example, you press F12 on a method in a referenced assembly.) It provides the method signatures, properties, fields, etc from the types, without providing any of the actual implementation.
As written, the code you posted wouldn't even compile in C#.
If from the metadata, it's not going to show you the implementation of the methods.
It looks like code but it is text based on the metadata in the assembly. It means that the IDE is unable to access the source code in question.

How can I declare a method then define it later?

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).

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.

Categories

Resources