Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 221
  • Last Modified:

Easy Question I think

How come some methods like: .ToLower() don't require a namespace but one such as: .WriteLine() does?
0
chilled2003
Asked:
chilled2003
  • 2
  • 2
1 Solution
 
smitty22Commented:
ToLower operates on string objects, while WriteLine is a static method that is part of the Console class.  The full specification of WriteLine is
  System.Console.WriteLine().
This is because Console is a member of the System namespace.  However, since System is usually always included as a using directive, you can just write Console.WriteLine().

String is also part of the System namespace, but the ToLower method is not static -- in other words, it operates on instantiated members of the String class.  This is why you can do things like
  string s = "Hello";
  s.ToLower();
--BUT NOT--
  String.ToLower();


0
 
kellycoinguyCommented:

String.ToLower is in System.String
Console.WriteLine is in System.Console
both in the System namespace.

I believe if you put:
using System;

at the top of your file, you shouldn't need to specify a namespace just the object:

Console.Writeline("..."); // this works fine for me

Can you be more specific about what you are required to do here?

-Kelly
0
 
chilled2003Author Commented:
Not really required to do anything just trying to learn C# :)  If .ToLower(); is in the System namespace then how come I cant put:

System.String.ToLower();
or
String.ToLower();

If it's part of System then how come if I dont include System as a namespace it still works with just .ToLower(); ?  But if I do that with WriteLine(); it errors and I have to put System.Console.WriteLine();
0
 
smitty22Commented:
.ToLower belongs to the String class, which in turn belongs to the System namespace.  You can use string methods without a "using System;" directive because they are an exception -- they are handled almost like a primitive type such as int or double.  The "using System;" directive is implied when working with strings as primitive types.

For instance, without a using System directive you can do:
  string str = "this is a string";  // note lowercase "string"
  System.Console.WriteLine( str.ToLower() );  // or any other string method
BUT NOT
  String s = new String("this is not valid");  // compiler error: "missing a using directive"
0
 
chilled2003Author Commented:
Thanks, that cleared it up for me :)
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now