How to Segment the Elements Iterated Over in a Foreach Loop

Create dynamic variable name

C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();

for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}

var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}

Dynamic variable into a dynamic type

You can do this - but it would be incredibly difficult (at least if you want to do anything usefully dynamic - just assigning a value to a local varaible would be easy enough, but I assume your real code would do more than that). Dynamic typing is handled by the C# compiler; there's no IL for it... whereas Reflection.Emit is all about generating IL.

So this piece of code:

static void Main()
{
dynamic x = "foo";
dynamic y = x.Substring(1, 2);
}

generates the following IL - as well as a generated class, referred to in the IL:

.method private hidebysig static void  Main() cil managed
{
.entrypoint
// Code size 109 (0x6d)
.maxstack 9
.locals init (object V_0,
object V_1)
IL_0000: nop
IL_0001: ldstr "foo"
IL_0006: stloc.0
IL_0007: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>> Program/'<>o__0'::'<>p__0'
IL_000c: brfalse.s IL_0010
IL_000e: br.s IL_0054
IL_0010: ldc.i4.0
IL_0011: ldstr "Substring"
IL_0016: ldnull
IL_0017: ldtoken Program
IL_001c: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
IL_0021: ldc.i4.3
IL_0022: newarr [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo
IL_0027: dup
IL_0028: ldc.i4.0
IL_0029: ldc.i4.0
IL_002a: ldnull
IL_002b: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags,
string)
IL_0030: stelem.ref
IL_0031: dup
IL_0032: ldc.i4.1
IL_0033: ldc.i4.3
IL_0034: ldnull
IL_0035: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags,
string)
IL_003a: stelem.ref
IL_003b: dup
IL_003c: ldc.i4.2
IL_003d: ldc.i4.3
IL_003e: ldnull
IL_003f: call class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo::Create(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags,
string)
IL_0044: stelem.ref
IL_0045: call class [System.Core]System.Runtime.CompilerServices.CallSiteBinder [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.Binder::InvokeMember(valuetype [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags,
string,
class [mscorlib]System.Collections.Generic.IEnumerable`1<class [mscorlib]System.Type>,
class [mscorlib]System.Type,
class [mscorlib]System.Collections.Generic.IEnumerable`1<class [Microsoft.CSharp]Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)
IL_004a: call class [System.Core]System.Runtime.CompilerServices.CallSite`1<!0> class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>>::Create(class [System.Core]System.Runtime.CompilerServices.CallSiteBinder)
IL_004f: stsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>> Program/'<>o__0'::'<>p__0'
IL_0054: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>> Program/'<>o__0'::'<>p__0'
IL_0059: ldfld !0 class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>>::Target
IL_005e: ldsfld class [System.Core]System.Runtime.CompilerServices.CallSite`1<class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>> Program/'<>o__0'::'<>p__0'
IL_0063: ldloc.0
IL_0064: ldc.i4.1
IL_0065: ldc.i4.2
IL_0066: callvirt instance !4 class [mscorlib]System.Func`5<class [System.Core]System.Runtime.CompilerServices.CallSite,object,int32,int32,object>::Invoke(!0,
!1,
!2,
!3)
IL_006b: stloc.1
IL_006c: ret
} // end of method Program::Main

You'd have to write Reflection.Emit code to generate all that IL yourself. I really, really don't think you want to do that.

see what type is a dynamic variable c#

That approach is fine (i.e. var1 is double), though that's usually not what dynamic is meant to accomplish. More often, you should dynamic when you do know what the type will be, but it's difficult or impossible to show that at compile-time (e.g. a COM interop scenario, a ViewBag in MVC, etc.) You could just use object if you want to pass a variable of unknown type. Otherwise, the run-time will do the type analysis for you during execution, which can be a big performance hit if that's not what you need.

In general, there could be scenarios where you'd want to use dynamic as a catch-all container, but this doesn't appear to be one of them. In this case, why not have a number of method overloads that each take the desired type:

void someMethod(double d) { ... }
void someMethod(int i) { ... }

Is there a way to test if a variable is dynamic?

Firstly, you need to separate the variable and the object. A variable is dynamic if it is defined as dynamic. That is all. There is nothing more. A field or property would be annotated with the [Dynamic] attribute, i.e.

public dynamic Foo {get;set;}

is actually:

[Dynamic]
public object Foo {get;set;}

This basically acts as a prompt for the compiler to access the object via the dynamic API rather than via the OOP API.

An object supports full dynamic capabilities if it implements IDynamicMetaObjectProvider - however, such an object can be accessed via both the dynamic API and via the regular OOP API (it can have both). Equally, an object that doesn't implement IDynamicMetaObjectProvider can be accessed via either API (but: only the public members will be available via dynamic).

Converting a dynamic Variable to Listmodel or array

Delete the Array Part in Your JS Script and Write it Like this :

var receipt = [
{ 'Service': 'Saab', 'Order': '20' },
{ 'Service': 'Volvo', 'Order': '12' },
{ 'Service': 'BMW', 'Order': '25' }
];

in this shape you are sending an Object. in your code i guess you are sending an JArray So it Will make some Problems in Converting from JArray to another Type .

in your API Side , Edit Your Code As Below :

public string Receipt_Turn(object r)
{

//important Line Here
List<Receipt> rr = JsonConvert.DeserializeObject<List<Receipt>>(r.ToString());

if (rr != null)
{
return rr[1].ToString();
}
else
{
return "false";
}

}

as you can see, we get it Like an Object and then we will be able to Get Ready your DeserializeObject part Like i mentioned.

you most declare a List of your Model, and after part DeserializeObject add that Type You want to Convert it to.

here Cause we Declared List<Receipt> , we should convert our DeserializeObject to it, so we add <List<Receipt>> after DeserializeObject.

and Finally you can use it Like You wish .

string serv = rr[1].Service;

How does having a dynamic variable affect performance?

I've read dynamic makes the compiler run again, but what it does. Does it have to recompile whole method with the dynamic used as a parameter or rather those lines with dynamic behavior/context(?)

Here's the deal.

For every expression in your program that is of dynamic type, the compiler emits code that generates a single "dynamic call site object" that represents the operation. So, for example, if you have:

class C
{
void M()
{
dynamic d1 = whatever;
dynamic d2 = d1.Foo();

then the compiler will generate code that is morally like this. (The actual code is quite a bit more complex; this is simplified for presentation purposes.)

class C
{
static DynamicCallSite FooCallSite;
void M()
{
object d1 = whatever;
object d2;
if (FooCallSite == null) FooCallSite = new DynamicCallSite();
d2 = FooCallSite.DoInvocation("Foo", d1);

See how this works so far? We generate the call site once, no matter how many times you call M. The call site lives forever after you generate it once. The call site is an object that represents "there's going to be a dynamic call to Foo here".

OK, so now that you've got the call site, how does the invocation work?

The call site is part of the Dynamic Language Runtime. The DLR says "hmm, someone is attempting to do a dynamic invocation of a method foo on this here object. Do I know anything about that? No. Then I'd better find out."

The DLR then interrogates the object in d1 to see if it is anything special. Maybe it is a legacy COM object, or an Iron Python object, or an Iron Ruby object, or an IE DOM object. If it is not any of those then it must be an ordinary C# object.

This is the point where the compiler starts up again. There's no need for a lexer or parser, so the DLR starts up a special version of the C# compiler that just has the metadata analyzer, the semantic analyzer for expressions, and an emitter that emits Expression Trees instead of IL.

The metadata analyzer uses Reflection to determine the type of the object in d1, and then passes that to the semantic analyzer to ask what happens when such an object is invoked on method Foo. The overload resolution analyzer figures that out, and then builds an Expression Tree -- just as if you'd called Foo in an expression tree lambda -- that represents that call.

The C# compiler then passes that expression tree back to the DLR along with a cache policy. The policy is usually "the second time you see an object of this type, you can re-use this expression tree rather than calling me back again". The DLR then calls Compile on the expression tree, which invokes the expression-tree-to-IL compiler and spits out a block of dynamically-generated IL in a delegate.

The DLR then caches this delegate in a cache associated with the call site object.

Then it invokes the delegate, and the Foo call happens.

The second time you call M, we already have a call site. The DLR interrogates the object again, and if the object is the same type as it was last time, it fetches the delegate out of the cache and invokes it. If the object is of a different type then the cache misses, and the whole process starts over again; we do semantic analysis of the call and store the result in the cache.

This happens for every expression that involves dynamic. So for example if you have:

int x = d1.Foo() + d2;

then there are three dynamic calls sites. One for the dynamic call to Foo, one for the dynamic addition, and one for the dynamic conversion from dynamic to int. Each one has its own runtime analysis and its own cache of analysis results.

Make sense?

Variable in the dynamic string in C#

Assuming I'm understanding, i think the String.Inject class could be helpful. Picture a named String.Format:

"Hello, {company}!".Inject(new { company = "StackOverflow" });
// "Hello, StackOverflow!"

The other benefit is you can have a hard-coded model and reference direct properties of it. e.g.

class Contact
{
string FirstName;
string LastName;
}

String greeting = "Mr. {FirstName} {LastName}, Welcome to the site ...";
String result = greeting.Inject(new Contact
{
FirstName = "Brad",
LastName = "Christie"
});

Creating dynamic variable names in C#

If you stick to your current design (CSV + dictionary) you could use the ExpandoObject class to get what you are looking for, create a simple factory class:

public static class ObjectFactory
{
public static dynamic CreateInstance(Dictionary<string, string> objectFromFile)
{
dynamic instance = new ExpandoObject();

var instanceDict = (IDictionary<string, object>)instance;

foreach (var pair in objectFromFile)
{
instanceDict.Add(pair.Key, pair.Value);
}

return instance;
}
}

This factory will create an object instance of whatever dictionary you give it, i.e. just one method to create all your different kinds of objects. Use it like this:

   // Simulating load of dictionary from file
var actorFromFile = new Dictionary<string, string>();

actorFromFile.Add("Id", "1");
actorFromFile.Add("Age", "37");
actorFromFile.Add("Name", "Angelina Jolie");

// Instantiate dynamically
dynamic actor = ObjectFactory.CreateInstance(actorFromFile);

// Test using properties
Console.WriteLine("Actor.Id = " + actor.Id +
" Name = " + actor.Name +
" Age = " + actor.Age);
Console.ReadLine();

Hopes this helps. (And yes she was born 1975)

use Dynamic variable to create a tuple-like variable

The Tuple data structure is present since long back, so even if you are targeting .net Framework 4 (C# 4.0), you should be good.

Only the new nice syntax and re-implementation as a value type were introduced later.

Said that:

var mustEncodeDict = new Dictionary<string, Tuple<bool, int>>();
mustEncodeDict.Add("test1", Tuple.Create(true, 3));


Related Topics



Leave a reply



Submit