Learning OOP - why is string.Join static, while string.Spit is not?

  • Thread starter Thread starter Epson Barnett
  • Start date Start date
E

Epson Barnett

I'm working on learning .NET and I'm curious about the reason for
using static methods in some cases. Specifically, the string class has
a split and a join method, but only the join method is static.

Both methods return a new string which is based on another string. It
would seem that both should not be static.

string mystring = "one, two, three, four";
string[] newstring = mystring.Split(',');

why not:

string[] mystring = new string[] {"one", "two", "three", "four"};
string newstring = mystring.Join(',');

I'd like to understand the underlying reason.

Thanks,
Epson
 
Epson Barnett said:
I'm working on learning .NET and I'm curious about the reason for
using static methods in some cases. Specifically, the string class has
a split and a join method, but only the join method is static.

Both methods return a new string which is based on another string. It
would seem that both should not be static.

string mystring = "one, two, three, four";
string[] newstring = mystring.Split(',');

why not:

string[] mystring = new string[] {"one", "two", "three", "four"};
string newstring = mystring.Join(',');

I'd like to understand the underlying reason.

Well I'll suggest it is because in your join example mystring isn't an
object of type String. It's a string array.

Split acts upon a string, so it is a method of a string. Join acts on a
string array and therefore it doesn't require a string to be defined. If it
did it would be an arbitrary instance of string used only to call the
method.

Tom
 
Epson Barnett said:
I'm working on learning .NET and I'm curious about the reason for
using static methods in some cases. Specifically, the string class has
a split and a join method, but only the join method is static.

Both methods return a new string which is based on another string. It
would seem that both should not be static.

string mystring = "one, two, three, four";
string[] newstring = mystring.Split(',');

why not:

string[] mystring = new string[] {"one", "two", "three", "four"};
string newstring = mystring.Join(',');

I'd like to understand the underlying reason.

mystring here isn't a string, it's a string array - so you couldn't
have an instance method in string which worked that way. The only
single string parameter is the string which is used between each
element. In theory you could therefore have:

string newstring = ",".Join (mystring);

but that's hardly natural.

The thing is, when you descibe Join, you naturally talk about it
working "on" a collection of strings. When you describe Split, you
naturally talk about it working "on" a single string - it's therefore
appropriate for Split to be an instance method, but Join not to be.
 
Back
Top