Extension method makes LINQ break

I think I hit the corner of extension methods and LINQ.

Today I announced some extension methods to make my code more readable. So I created an extension method that gets the object and does a direct listing:

 
public static class GeneralExtensions
{
    public static T Cast<T>(this object o)
    {
        return (T)o;
    }
}

The goal was to be able to call my direct castings something like this:  

MyObject.CastTo<MyInterface>();

It happens that in the same namespace I have an extension method that has a LINQ expression

using System;
using System.Collections.Generic;
using System.Linq;

public static class EnumExtenstions
{
    public static IEnumerable<string> UseLinq(this IEnumerable<object> collection)
    {
        return (from object value in collection select value.ToString() ).ToList();
    }
}

Adding this first extension method to my code base will result in the following error

Error   CS1936  Could not find an implementation of the query pattern for source type 'object'.  'Select' not found.    

Having both extension methods in different namespaces (and without referring) or renaming Castsomething else solves the problem.

, . LINQ? , Cast ?

.NET Fiddle ()

+4
1

, . LINQ?

!

from Foo bar in blah select baz

:

blah.Cast<Foo>().Select(bar => baz)

, . blah Cast, ; , .

, ?

, - ", ". , LINQ System.Linq, . , "" . System.Linq, "" , System.Linq, .

, , # "". ", Cast, , , Select, Cast, ?" # , Cast , Cast, . , , . # , , .

, , "" . , .

, . "", "", "" .., LINQ .


UPDATE: , : , , , .

, , :

  • Cast<int>(123) int; (int)123 .
  • Cast<short>(123) , (short)123 . int .
  • , Animal Shape. Cast<Shape>(new Tiger()) , (Shape) new Tiger() .
  • , q nullable int, null. Cast<string>(q) ! (string)q

. , . , dynamic, .

+12

Source: https://habr.com/ru/post/1626396/


All Articles