Reputation: 167
I just started learning C# and I saw something like this:
public class Name
{
string FirstName {get; set;}
}
VS
public class Name
{
FirstName FirstName {get; set;}
}
Can someone explain the difference between the two? When to use one vs the other?
Upvotes: 3
Views: 293
Reputation: 38850
The first one declares that the property is of type string
:
string FirstName {get; set;}
The second declares that the property is of type FirstName
:
FirstName FirstName {get; set;}
So I imagine your scenario is like this:
public class Name
{
public FirstName FirstName {get;set;}
public LastName LastName {get;set;}
}
public class FirstName
{
public string Name {get;set;}
}
public class LastName
{
public string Name {get;set;}
}
In C# there are two kinds of data types: 1. Inbuilt - they are part of the language. 2. User-defined - they are part of your code, or the code of a library you are using.
String
(or, to use its fully qualified name: System.String
) is part part of the language itself. Some types are part of the .NET framework and you can, for all intents and purposes, consider these the same as 1.
Other types are defined in code, or the code of third-party libraries that you use. These are considered to be user-defined types. In your case, FirstName
will be a user-defined type (probably a class
or a struct
).
Upvotes: 6
Reputation: 19384
I give you as simple answer as can be. Here FirstName FirstName {get; set;}
you have
FirstName // type identifier
FirstName // identifier
{get; set;} // access modifier
Since FirstName
in position of "type identifier" is a type. Your question boils down to, "what is difference between string
and FirstName
"?
Well, we all know the type called System.String
, shortly string
. It is provided by Microsoft. But what about FirstName
? What is the full namespace for it? Sort of like asking difference between string
and int
. They both types, both derive from object
but everything else is different.
Now, it is totally possible for a class as this
class FirstName
{
FirstName FirstName {get; set;}
}
In this case you have a class FirstName
that contains property FirstName
, which will return (if set) object of type FirstName
, which is of same object type as defined by class FirstName
, and which will contain a property FirstName
, and so on.
Upvotes: 1