"To" vs "As" vs "Get" Method Prefixes - c#

Does anyone know of any naming convention rules/guidelines that dictate when to use a "To" prefix (myVariable.ToList()), an "As" prefix (myVariable.AsEnumerable()), or a "Get" prefix (myVariable.GetHashCode())?

I assume there's no convention, so just use what fits best to what you're doing.
"To" creates something new/ converts it
"As" is just a "different view" on the same f.e. by using iterators
"Get" is a getter for everything else

My understanding/conventions:
"To" performs a conversion; A new object is created in memory, based on the data inherent in your source.
"As" performs a cast; The same reference passed in is returned behind the "mask" of a different type.
"Get" performs pretty much anything else that takes in a source and whose primary product is a transformed result. Gets can perform a calculation, return a child, retrieve data from a store, instantiate objects from a default state, etc. Not all such methods have to be named "Get", but most methods intended to calculate, instantiate, project, or otherwise transform, and then return the product as their primary purpose are "getters".

When myObj is not related to List, prefix "To" to convert.
When myObj is a subclass of Enumerable, prefix "As" to give it as Enumerable
When myObj is not related to List, but it composes / can compose List use "Get" prefix

If you're using Entity Framework for CRUD operations on a database, then using .ToList() will have your query be executed right there, as opposed to using AsEnumerable() which will use deferred execution until you actually try to access a record.
That's one that I thought of right off the top of my head.

As is a reinterpretation of existing data. AsEnumerable does nothing. It is implemented as return input;.
To implies a conversion.
Get does not imply any of the former.
You will find valid deviations from these rules. They are not set in stone.

I would say that To vs As has more to do with differences like class vs interface
i e you are saying AsEnumerable when you really want to return something that implements interface.
ToList on opposite returns new object which is representation of current state of current object, ie ToDictionary just another way of representing same data.
Third ones Get methods returns some properties of the object OR something about part of it's state and not the full state.

Related

Cast an Interface and IQueryable<Interface> to its concrete implementation [duplicate]

I know about covariance, and I know that in general it will not be possible in C# until v4.0.
However I am wondering about a specific case. Is there some way of getting converting IQueryable<Derived> to IQueryable<Base> by somehow creating a wrapper class that does not actually perform a query, but can actually "pass through" a .Where<>() call?
My use case is that I am trying to deal with a database schema that has many similar tables. Most of the fields are in common, and many of the common fields need to be queried on each table. I'm using LinqToSql. I was hoping to avoid duplicating all the queries for each table.
Is the following what you are looking for?
var results = queryable.OfType<Base>.Where(...);
The OfType method will gather up anything that is of the specified type, and if all items in the collection are either of type Base, or derived from type base, they should qualify. In the subsequent where, all items would be of type Base.
The following will also work, altough it is less pretty:
var results = queryable.Select(derived => (Base)derived).Where(...);

Access <AnonymousType> fields

I have an AnonymousType object that contacts two fields with their values. How can I access the value of these fields?
Ex:
SourceTypeObject { Source_Type_Id = 1, Source_Type_Name = "bibliography" }
I need to do something like : SourceTypeObject.Source_Type_Id
Is that possible?
EDIT:
Here's what I get if I tried to access the property directly:
Yes, this is the exact purpose of anonymous types. The only thing that might prevent you from doing so is if you passed the anonymous type around as a parameter with type "object". This would hide information about the anonymous type, and it would look like just any old object then.
The only recourse if this is the case is to use reflection, which is slow and awkward. Anonymous types are a meant to be a very "local" phenomenon, and if you find yourself wanting to use them elsewhere in the program, it's worth the time to promote it to a real type.
EDIT: In response to the image you posted, assuming the array is declared locally just outside of view, try to replace the object SourceTypeObject with var SourceTypeObject. This allows it to infer the anonymous type instead of being told that it's an object.

List<dynamic> elements have fields but I cannot access them. Why?

I need to loop over a List<dynamic> objects.
The list's objects all have values, but for some reason, I am not able to access any of the dynamic object fields. Below is a screenshot of my debug window:
There you can see the object contains fields (such Alias, Id, Name, etc).
I tried both casting it to a IDictionary<string, object> and ExpandoObject, to no avail. I did not face such a thing before: failing to access existing fields in a dynamic object when they exist.
What is wrong here?
The code is throwing a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException with a message stating {"'object' does not contain a definition for 'Name'"}.
The list was created adding anonymously-typed objects, like this:
return new List<dynamic>(fields.Select(field => new
{
Id = field.Id,
Alias = field.Alias,
Name = field.Name,
Type = field.Type,
Value = field.Value,
SortOrder = field.SortOrder
}));
where fields is an ICollection<Field>, a strongly-typed collection.
The telling part is the exception:
{"'object' does not contain a definition for 'Name'"}.
This indicates that the runtime binder was not actually capable of accessing the type you're passing in dynamic (since dynamic does actually enforce visibility rules).
The most likely cause of this is that you're creating the anonymous type in a different assembly from the one where you're subsequently reading it - since anonymous types are declared internal, the consuming assembly cannot access it, causing the error message above.
Contrast with the usual case of runtime binder exceptions:
'<>f__AnonymousType0< string >' does not contain a definition for 'Name'
EDIT:
A possible solution to the problem is to use the InternalsVisibleToAttribute on the assembly containing the anonymous type. However, this is code smell - just like any other use of InternalsVisibleToAttribute or internal itself.
A better way would be to make sure you don't actually pass anonymous types over assembly boundaries - after all, they shouldn't even be used outside of the method they originated from; the fact that they are is basically an implementation detail of .NET - they didn't have another way to do the same thing. This could change in future versions, making the InternalsVisibleToAttribute solution doubly unreliable.
The way your code is using dynamic suggests that your team has flawed assumptions about how dynamic works and how it's supposed to be used. Note how the actual runtime type of List<dynamic> is actually List<object>. The same goes for arguments of type dynamic (which are again just object, albeit marked with DynamicAttribute). And in fact, that really is what dynamic is - it's a way to handle runtime dynamic dispatch - it's not a property of the type or anything, it's just the way you actually invoke whatever you're trying to invoke. For C#, dynamic allows you to skip most of the compiler checks when working with those dynamic types, and it generates some code to handle the dispatch for you automatically, but all of that only happens inside the method where you actually use the dynamic keyword - if you used List<object>, the end result would be exactly the same.
In your code, there's no reason not to use simple static types. Dynamic typing doesn't really give you any benefits, apart from the effort to code the types themselves. If your co-workers don't like that, well, they should present a better solution - the problem is quite obvious, and it's something you need to deal with.
Much worse, it explicitly hides all context, all the type information. That's not something you want in an API, internal or not! If you want to hide the concrete types being used, why not - but you should still expose an interface instead. I suspect this is the reason why anonymous types can't implement interfaces - it would encourage you to go entirely the wrong way.

Find all static references to a class by code c#

I search for a way to display all static occurances of classes (similiar to the Visual Studio functionality: find all references).
It should only be by code and not manually.
I want to
Only list classes with a specific attribute
List all classes which have static references to it (find table bindings to data classes)
My first step is to list all Types which i'm interested in:
var result = from t in assembly.GetTypes()
where t.IsDefined(typeof(TAttribute), inherit)
select t;
return result.ToList();
I'm having problems with the second step.
I know how to find Properties... from a class. But how is it possible to go the other way round, and find all usages of a class?
You can not find static references using reflection, it's something that AST may know about. For this you may want to use: Roslyn (Compiler as a Service), that let's you compile, and investigate AST.
You can't find references in method bodies using reflection but you can find fields, properties and methods parameters/return values.
You already know how to list all types, now for each type:
Type.GetProperties returns an array of PropertyInfo, you can check if `PropertyInfo.ProeprtType' is in the list of types you care about.
Same goes for fields with Type.GetFields
For methods you call Type.GetMethods, this returns an array of MethodInfo objects, to get the return type you check MethodInfo.ReturnType and for the parameters call MethodInfo.GetParameters and ParameterInfo.ParameterType
That's only leaves local variables defined inside method bodies and those cannot be accessed with reflections

Using LINQ's Except<> method with an object from an external API

I have a List<> of HTMLAnchor objects (HTMLAnchor is an object from an external API). I want to exclude clicking on some of the links as they are for logging out, etc.
Using LINQ, I can use the Except operator. However, on here (http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#except1), the example using the custom type (Product if I remember correctly) does not use the overloaded version of Except.
Furthermore, if I am using a type not defined by me, do the rules change? And should the class I write to implement IEquality have the same name I am trying to exclude in my generic collection (HtmlAnchor)?
Thanks
If you want to compare anchors using the default Equals method, which in this case will probably give you reference equality, you don't need to do anything: just pass the set of anchors to exclude:
anchors.Except(anchorsToExclude);
If the members of the sequence to exclude will not be reference-equal (or whatever HtmlAnchor.Equals deems equal), the interface you want to implement is IEqualityComparer<T>. This exists precisely to allow you to provide a custom equality comparison for a type that you don't define, so the rules don't change -- you just have to use the appropriate overload of Except.
So you would create a class called e.g. HtmlAnchorEqualityComparer which implements IEqualityComparer<HtmlAnchor>, and pass an instance of that to Except:
anchors.Except(anchorsToExclude, new HtmlAnchorEqualityComparer())
When you don't have control over the type, and the default equality operations do not suffice (ie. Equals is not properly implemented), you should use the overload which takes an IEqualityComparer<T> parameter. This is a class that you can implement yourself to provide the definition of equality, that you need.

Categories

Resources