Accessing Form public property with var

rg0920

New member
Joined
Nov 1, 2021
Messages
1
Programming Experience
Beginner
I am new to c#, I am wondering why is it that if I use var type to create new Form instance I am able to access a public property, but cannot see the property if I use Form type?

var form = new Form1(); // I am able to access public property


Form form = new Form1(); // I cannot access public property
 
That's because Form is the base type of Form1. Form will not have any of the properties that Form1 has. Change your code to:
C#:
Form1 form = new Form1();

When you use var, the compiler knows to make the form the correct Form1 type.
 
Last edited:
var means type is inferred, implicitly typed, from what is assigned.

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
 
Back
Top Bottom