-2

I am trying to extend the System.String and add one more static field String.Space which represents a single space " " just like how Microsoft implemented String.Empty in the namespace Using System;. I am not able to implement this extension please help.


I wanted to implement a kind of field extension...

enter image description here

wanted the result like

enter image description here

Rahul Uttarkar
  • 3,367
  • 3
  • 35
  • 40
  • 2
    What have you tried so far? What do you mean by "not able to implement"? Please elaborate – logix Oct 05 '17 at 16:51
  • 2
    I'd also as *why* you'd want to do this? – DiskJunky Oct 05 '17 at 16:51
  • 1
    Check for answers here: https://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class – Tony Morris Oct 05 '17 at 16:52
  • Possible duplicate of [Can I add extension methods to an existing static class?](https://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class) – Tyler Lee Oct 05 '17 at 16:54
  • @TylerLee OP wants to add a static field, not an extension method. – Xiaoy312 Oct 05 '17 at 16:57
  • @Xiaoy312 the linked question accurately states that you cannot add static anything to static types via extensions, thus answering OPs question. If you read the question, it's talking about adding methods to `Console`, which is similar to the use case here. – Tyler Lee Oct 05 '17 at 17:02
  • 1
    @TylerLee While it did answer the question, it does not necessarily make this question a duplicate. – Xiaoy312 Oct 05 '17 at 17:05
  • @DiskJunky I was trying to implement computational fake property FullName for Employee object which is with the combination of NamePrefix, FirstName, Middlename LastName.. NameSuffix etc. Since i wanted a separate space but code did not look good with " " so i wanted to extend and add read only property like String.Space to make consistent code standard. – Rahul Uttarkar Oct 05 '17 at 18:27
  • @logix I have included the codes snaps which provides clear idea that i was looking for. – Rahul Uttarkar Oct 05 '17 at 18:53
  • @Tony Morris the method extention like "SomeString".Space() is not what i was looking for. i wanted some sort of field extention. – Rahul Uttarkar Oct 05 '17 at 18:58

4 Answers4

12

You could have a static class like so;

public static class Strings
{
    public const string Space = " ";
}

And use it in your code like;

FullName = FirstName + Strings.Space + MiddleName + Strings.Space + LastName;

However, the ultimate goal is to make the code maintainable, be reasonably efficient and reduce the likelihood of errors. With that in mind, it's best to reduce the number of concatenations and supply just the values that are needed. To that end a simple format string would be a cleaner approach; (pre C#6);

FullName = string.Format("{0} {1} {2}", FirstName, MiddleName, LastName);

And if C#6+;

FullName = $"{FirstName} {MiddleName} {LastName}";

Why would you use those last two approaches? Well, it comes down to separation of concerns. Leave the string formatting to string.Format() and simply supply the values you need. You reduce the likelihood of errors by having fewer components in the mix, decrease maintenance overhead by the same and increase efficiency by reducing the number of strings involved to perform the concatenation.

EDIT

As for "Why doesn't c# support extension properties?", I'd extract a quote from Lindos Pechos's link from the C# language development team;

It was of course immediately obvious that the natural companion to extension methods is extension properties. It's less obvious, for some reason, that extension events, extension operators, extension constructors (also known as "the factory pattern"), and so on, are also natural companions. But we didn't even consider designing extension properties for C# 3; we knew that they were not necessary and would add risk to an already-risky schedule for no compelling gain.

Basically it boils down to "There wasn't a compelling need" for extension properties to allow you to create something like string.Space. Maybe in future versions.

DiskJunky
  • 4,750
  • 3
  • 37
  • 66
  • Yes i do agree, but Microsoft implemented String.Empty even though we can work around use "" char. i was just provided simple example since @logix wanted to post it. – Rahul Uttarkar Oct 05 '17 at 19:11
  • @RahulUttarkar they did but a space would be a rarer use case than `""`. And as @LindosPechos said, there are reasons why there are no extension properties - which is what you're doing in the OP. – DiskJunky Oct 05 '17 at 19:14
  • 1
    @RahulUttarkar its a relic of past days. [This](https://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and-empty-string) might be interessting for you. – Christian Gollhardt Oct 08 '17 at 10:00
  • @ChristianGollhardt yes i was looking for similar thing for replacing " " with String.Space but im not able to implement in practical. – Rahul Uttarkar Oct 08 '17 at 16:01
  • 1
    I actually wanted to extend String object instead of creating Strings new class – Rahul Uttarkar Oct 12 '17 at 02:16
  • 1
    Your "better approach" is for C# 6, not 7. – Andrey Alonzov Oct 13 '17 at 08:52
3

Unfortunately the framework (v4.7 at the time of this writing) does not currently support extension properties/fields. See a good write up of this here "Why No Extension Properties?"

Which means you are limited to using an extension method. One such example:

namespace System.String
{
    public static class Extensions
    {
        public static string Space(this string s)
        {
            return " ";
        }
    }
}

Extension methods require an instance of an object. So it can be used as such:

// Returns " "
var space = "".Space();

Or

// Returns " "
var space = String.Empty.Space();

This falls into one of those "It's not pretty, but it works" categories.

Darren H
  • 450
  • 3
  • 5
  • 3
    What about a simple `var space = ' '`?; or another simple `var space = MyConstants.Space;` (with Space as a public readonly property of a class MyConstants)? Extension methods are just syntactic sugar to help you write more "pretty" code. using them to write "not pretty" code has no meaning IMHO. – Gian Paolo Oct 05 '17 at 19:00
  • 1
    @GianPaolo I completely agree. I personally would not use an extension in this regard. The OP wanted a property extension, I just provided an alternative that still fit the extension syntax. DiskJunky has it correct by providing the alternative non extension suggestions. – Darren H Oct 06 '17 at 15:32
1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringFunctions.Extensions
{
   public static class StringExtensions 
    {
        public static readonly string Space = " ";

        public static string  Spacemethod(this string name)
        {
            return string.Concat(name," ");
        }
    }
}

in the place use the Alias name of class String. Like

using String = StringFunctions.Extensions.StringExtensions;

small string it's reserved word, so, it's throw Error.if you getting String.Space w=it's work entire places of class, other string function call like string.Empty Your functions call String.Space like this

using String = StringFunctions.Extensions.StringExtensions;
namespace StringFunctions
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = String.Space;

        }

    }
}
umasankar
  • 599
  • 1
  • 9
  • 28
  • 1
    you only extend the methods not properties or fields in class. the only way set the alias name extend field like this type only. some reserved words are not working like small letter started string because it's already alias name of System.String – umasankar Oct 13 '17 at 13:46
  • Agreed, it would also cause issues for any system using a code convention of `String` rather than `string`. Still...very creative approach. – DiskJunky Apr 13 '19 at 21:09
0

I was able to do the following. You'll get a warning, but it compiles.

namespace System
{
    public static partial class String
    {
        public static string Space = " ";
    }
}

To call:

string sp = String.Space;
akerra
  • 1,017
  • 8
  • 18