Click here to Skip to main content
13,200,729 members (53,535 online)
Rate this:
Please Sign up or sign in to vote.
See more:
how can call form name from string variable?
Posted 24-May-12 0:48am
Updated 24-May-12 0:58am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Your question isn't at all clear, but I'm assuming you want to create a form using a string. If that's true:

var form = Activator.CreateInstance(Type.GetType("STRING_VARIABLE_HERE")).Unwrap() as Form;
if(form != null)
Ed Nutting 24-May-12 7:22am
My 5+ - Though I don't like the use of var (why not just do proper casting and strong typing, that's half the point of languages like VB.Net and C#). Anyway, looks like it should work :)
jim lahey 24-May-12 7:34am
The use of var in no way indicates a lack of strong typing. It's syntactic sugar for the compiler because you can infer the type from the cast that is performed. It's a standard part of C#.
Ed Nutting 24-May-12 12:47pm
The sue of var isn't strongly typing - it can hold any type, which is by definition therefore not strongly typing your variable. Using var when it is not necessary (which is always in .Net languages) makes code unreadable and hard to understand, especially as many people don't use casting or the as keyword with it. It may be standard in C# but it is a horrible thing to use, otherwise why bother with using proper types!? You call it a "syntactic sugar", I call it an abomination...
jim lahey 4-Jun-12 3:45am
I think you're confusing var and dynamic keywords. Of course var is strongly typed, assign something to a var and on the next line intellisense pops up with all the properties, methods and events for the type you just assigned, so I am definitely using proper types. as for readability my code reads just fine, but it's human nature to fear what you don't understand ;)
Ed Nutting 4-Jun-12 4:35am
What you say demonstrates you do not understand what strongly typing really means or are you about to argue that JavaScript is strongly typed? I have done far too much programming in JavaScript - I know exactly what var is, what it does and that is precisely why it shouldn't be used. By the way, Intellisense says nothing about whether something is strongly typed or even good code practice. Perhaps you should try programming without it for a while and tell you what, only use vars. I bet your code will have a lot more bugs, be significantly harder to maintain and grossly unreadable.
jim lahey 4-Jun-12 5:16am
Why are you talking about JavaScript? We're talking about C#. C# by it's very nature is strongly typed, whereas JavaScript is weakly typed. I suggest you take a look at the MSDN documentation that covers the use of var in C#: It's not weakly typed, it's implicitly typed which is still strong and static type checking still takes place. By contrast you can look at the typing discipline of JavaScript: By your logic, you might assume that JavaScript and SQL are the same because they both have the "function" keyword.

I understand that for some people it can be a little confusing and it's a preference thing "to var or not to var", but don't concern yourself with the quality of my code, it's maintainability or readability because that's my business, OK?
Ed Nutting 4-Jun-12 5:59am
Yes I know we are talking about C# but JavaScript and C# both contain the "var type" and in both languages they do the pretty much the same thing. C# is supposed to be strongly typed by nature but the var type introduces implicitly typed variables. These by definition are not properly strongly typed variables since strong typing means giving something a definite type, which var isn't. Implicitly typed variables are not strongly typed variables unless you have an IDE that forces it. Sadly the MSDN stuff is written with the prerequisite that you are using VS and nothing else and so is able to call implicitly typed variables strongly typed. var is only strongly typed in Visual Studio because Intellisense, pre-compiler and compiler all force it to be so. If I were to use notepad to produce C# code, using vars would make it hard to follow, impossible to maintain any idea of what type something was without going back and checking where I got it from every time and what type that was and furthermore there would be a lot of bugs through casually ignoring type that wouldn't be noticed until compile time. Even then you could have a compiler that lets you create a var, assign it one type of value then a completely different one on the next line and that'd be fine. If it were properly strongly typed, no-one making a compiler could even consider making it do that. Using var in C# is bad, plain and simple. If someone can't figure out what type something should be, they should look it up so that they actually understand what they are doing. The only reason vars work at all is because of Intellisense but outside of the narrow world of Visual Studio, not to say VS is bad, but it becomes a lot harder without it and code becomes worse generally. (Just to note, JavaScript is completely weakly typed, as you rightly point out, and look how unreadable most of the JavaScript people produce is!? And that's without mentioning how many bugs scripts have...)

Finally yes, it's perfectly okay by me, just don't try telling me what I don't understand because you know little, if not, nothing about me. (Though your own strong objection would suggest that the quality of your code isn't great and that you know it to be so.)

P.s. Just a final thing to point out is that with vars, when the compiler has a choice between types, it may not pick the one you want e.g. when it can choose between IEnumerable and IQueryable, which may be very significant for when data is actually retrieved from the database!
jim lahey 4-Jun-12 6:18am
So let me understand, you're saying the following would actually work?

var i = 0;
i = "Doesn't work";
Ed Nutting 4-Jun-12 6:42am
Indeed it would if it weren't for VS stopping you at every turn. I have a number of issues with this sort of code. Assume I am writing code in Notepad so there is no nice Intellisense or pre-compiler, just raw code.
1) That sort of potential bug, assigning the wrong type, is impossible to spot until compile time when I may get an error
2) Any given compiler may actually be able to compile that, in much the same way JavaScript can handle it. Because it is not truly strongly typed, it leaves it open to abuse.
3) If the example weren't so simple, actually knowing quickly and easily what type I could assign to i without working it out and writing it down somewhere may be very hard. Now writing down what type something is, rather than just explicitly typing it in the first place, is farcical. Also, Joe Bloggs who reads my code in future will also have to work out what type everything is. If it had just been explicitly typed in the first place none of this pointless effort would be wasted. This argument otherwise summarised as "vars make code far more unreadable and hard to maintain".

vars have their place. Their place should be sat in corner for everyone to look at, study, understand and then never return to unless by force. JavaScript demonstrates that vars can be powerful but also a nightmare. Developers should not be allowing the same chaos to enter C#. Too many poor or new developers fall in love with vars and end up in a mess, writing awful code. Not using vars is both good practice and good principle. I have never used them other than to learn about them and see no decent reason for them to be used, especially since I have never needed to use them and since I have answered too many problems which were a result of using vars. The problems probably wouldn't have occurred if explicit typing had been used, i.e. proper strong typing. Their only advantage is allowing developers to be lazy, which in this extreme, isn't a good thing.

As an end to this debate, it comes down to how you define strong typing. This Wikipedia page points out several, I think you can spot which I would say is correct. - See "Omission of implicit type conversion", which implies omission of implicit type declaration.
It seems you follow a looser definition that allows implicit types. A correct definition, but one which, in my opinion, does not lead to good code.

jim lahey 4-Jun-12 7:15am
You'll not be surprised to find out I still don't agree with you, and just so that I'm 100% sure I did the following:

In your favoured notepad IDE :) I created this file:

public class WTF
public WTF()
var i = 0;
i = "This won't work";

I compiled it with csc like this:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc /target:library /out:WTF.dll WTF.cs

csc then has a bitch at me:

WTF.cs(7,6): error CS0029: Cannot implicitly convert type 'string' to 'int'

So it's not just visual studio that prevents this. The basic C# compiler also doesn't like it. With things like this being caught at compile time as you allude to there is no way that using var could introduce bugs into the code, because if it doesn't compile, it doesn't even get checked in, let alone shipped. A few more pages from teh internets for you:

I've been using var since it came out and it hasn't caused me any problems whatsoever, you could say I've got a good handle on my var habit. I don't let my var habit interfere with my professional life but if it makes you happy, you can call me a dirty varhead. It's lunchtime here so I'm off into town to see if I can score some really good var, I just hope the the guy who ripped me off last time isn't there. I thought I was getting a good deal on some var but ended up with a bag full of Dim ;)
Ed Nutting 4-Jun-12 7:47am really didn't get what I said... I said that if you weren't using the VS compiler i.e. the default .Net compiler i.e. the one you just compiled with. I never denied that the compile wouldn't work. What I did say is that the bug wouldn't be found until compile time when, if using explicit types, the bug could have been spotted before compiling.

Regarding your articles, the first only seems to support my case that vars should not be used much (but I say not at all). The second may justify your point, but is proved totally wrong by the first article so really all you have done is harm your case for using vars. Vars should not be used. End of.

As regards to what I think of you, you give an extreme opinion. While I dislike the use of var (clearly), your code may still be good and valid. You appear to be a good programmer, however, I still uphold that the use of var, more often than not, leads to poor code and poor programmers. Just look at the author of the second article, it doesn't seem like he had a clue that what he was doing could cause major issues.

A good example would be if I were getting data from a database, I could either get it as an IQueryable or as a List. IQueryable uses lazy-load effectively, so the data isn't retrieved from the database until it is explicitly needed. Also, methods like Count fire extra database queries to return the result. On the other hand List gets the data immediately in one database request. Now both of these are useful for different things but suppose I was going to loop through all the items from the database. If I used IQueryable, it would result in a separate database query for every item. If, however, I used a list, I would get only one, bulk query at the very start. So clearly List is better here. However, the use of var in code could end up disguising which type I was actually using as the compiler may just make it into an IEnumerable, which could be either IQueryable or List. I am left not knowing which was returned. However, if I explicitly made the type used a List, I would have no worries and all other coders who came to look at my code would know exactly what it was doing. Here we see an intended use for var that actually ends up worse than if the programmer thought about what he/she was doing with types rather than just using var.

Anyway, enjoy your lunch and happy coding :)
Mostafa Meshkat 24-May-12 7:38am
thank you for answer :)
I have 2 forms in, I want calling my form 2 by using string variables(dim str as string)
I don't like using direct name:

dim frm as new form2
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Unless you have a good reason to activate types (forms in this case) based on a string, I would strongly recommend not to do this.

Using a string variable makes your code vulnerable to different kinds of errors, for example spelling mistakes in the string. These are not detected by the compiler since the form name is 'hidden' inside a string.

Personally I would prefer rethinking the need for this and possibly use generics instead. For example if you need to have a common method for all forms, you cound define a generic method that accepts any Form but only Form.

For information about generics, see Generic Types in Visual Basic[^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 3


Please Try This.

I have create two form in my Application which is below.,
Form1 and Form2.
In this application WindowsFormsApplication2 is my namespace.

In Form1 contain one Button And this button's click event i open form2.
In Button click event looks like..

var newForm = Activator.CreateInstance(Type.GetType("WindowsFormsApplication2.Form2")) as Form;
            if (newForm!= null)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.171020.1 | Last Updated 29 Oct 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100