0

My First Version :

bool IsDynamicType(object obj){
    return obj is dynamic;
}

it's fault because all class object will return true,ex:

var b1 = new {} is dynamic; //True
var b2 = new object() is dynamic; //True

I know new {} system will compiler <>f__AnonymousType01.
My current way to check object is dynamic :

bool IsDynamicType(object obj){
    return Regex.IsMatch(obj.GetType().Name,@"AnonymousType");
}

I am having a problem now if class's name is xxxAnonymousTypexxx this function will return true.

Wei Lin
  • 3,591
  • 2
  • 20
  • 52
  • You mean you want to check for an _anonymous_ type, right? Not `dynamic`. – Sweeper Dec 19 '18 at 03:49
  • `dynamic` doesn't remove strong typing from C#. Each instance still have exactly one type. Also, it's looks like you trying to determine is type of object is anonymous? – vasily.sib Dec 19 '18 at 03:49
  • @Sweeper sorry, i have no idea the different between dynamic and anonymous – Wei Lin Dec 19 '18 at 03:51
  • An object cannot be dynamic, only the variable to which it is assigned. – Cᴏʀʏ Dec 19 '18 at 03:53
  • 1
    `dynamic` means: "Hey CLR, I'm sure you can handle the type of object on the go, but I guess it will have a `Name` property" `anonymous` means: "Hey CLR, I don't care how you call this type but it must contains a string `Name` property" – vasily.sib Dec 19 '18 at 03:55
  • @Cory i got you,i fix the title `How to check if an Object is a AnonymousType`,thanks. – Wei Lin Dec 19 '18 at 03:56
  • 2
    @ITWeiHan indeed you've likely already found your answer (https://stackoverflow.com/questions/2483023/how-to-test-if-a-type-is-anonymous) to the question you actually interested in (not the one asked originally in the post which was also [duplicate](https://stackoverflow.com/questions/19785655/is-there-a-way-to-test-if-a-variable-is-dynamic)). If you still need more info - consider asking new question using correct terms. – Alexei Levenkov Dec 19 '18 at 04:03
  • @Alexei Levenkov , thank you! – Wei Lin Dec 19 '18 at 04:26

0 Answers0