Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Method - Cannot implicitly convert type 'string' to T

May be a simple question..

I have an interface:

public interface ISanitizer
{
    T Sanitize<T>(T data_);
}

And an implementing class:

    public class BasicFilenameSanitizer : ISanitizer
    {

        private readonly String m_replacementCharacter = String.Empty;

        public BasicFilenameSanitizer(String replacementCharacter_)
        {
            if (replacementCharacter_ == null)
            {
                throw new ArgumentNullException("replacementCharacter_");
            }

            m_replacementCharacter = replacementCharacter_;
        }


        public virtual T Sanitize<T>(T filename_)
        {
            if (filename_ == null)
            {
                throw new ArgumentNullException("filename_");
            }

            Regex invalidCharacterRegex =
                new Regex(String.Format("[{0}]", Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()))));

//error occurs here
            return Regex.Replace(filename_.ToString(), invalidCharacterRegex.ToString(), m_replacementCharacter);
        }

}
like image 292
adamwtiko Avatar asked Apr 17 '26 02:04

adamwtiko


2 Answers

In my particular case the following code generated the same error:

return (T) someData;

What helped me out - double cast with object:

E.g:

    static T MyFunction<T>() {
        string s = "test";

        if (typeof(T) == typeof(byte[]))
            return (T)(object)System.Text.Encoding.ASCII.GetBytes(s);
        else if (typeof(T) == typeof(string))
            return (T)(object)s;
        else throw new Exception();
    }

...

            var ba = MyFunction<byte[]>();
            var bs = MyFunction<string>();
like image 148
Stefan Michev Avatar answered Apr 18 '26 15:04

Stefan Michev


In your code you are returning a string from a generic type which could be anything.

Change your code to this if you want a generic return type:

public interface ISanitizer<T>
{
    T Sanitize(T data_);
}

public class BasicFilenameSanitizer : ISanitizer<string>

If you simply want to always return a string you only need to change the method return type:

public interface ISanitizer
{
    string Sanitize<T>(T data_);
}

public virtual string Sanitize<T>(T filename_)
like image 25
Oded Avatar answered Apr 18 '26 16:04

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!