0

I have a class which consists only of string constants. Call it Class A. I declare following variable in here.

public static string SetScore = $"Score[@Set='{currentSet}']";

There is another class, lets call it Class B. I will use my SetScore variable in class B. now this class B knows what is currentSet.

Problem is Class A does not know what is 'currentSet'.

Is there any solution to this, other than to declare SetScore in class B OR using String.Format?

10
  • 1
    Does $"Score[@Set='{MyConstantStringClass.currentSet}']" not work? Commented Mar 22, 2018 at 6:47
  • How about : public static string CurrentSet { get; set; } public static string SetScore = string.Format("Score[@Set='{0}']", CurrentSet); Commented Mar 22, 2018 at 6:49
  • @Orphid, the value of currentSet is not constant. It will change. Commented Mar 22, 2018 at 6:53
  • 1
    Do you really want to use string interpolation? You can use String.Format() method Commented Mar 22, 2018 at 6:54
  • @Praneet, are you saying to declare currentSet in same class where SetScore is declared?? that will kill the purpose, I dont know the value of this currentSet. Commented Mar 22, 2018 at 6:54

1 Answer 1

4

You can't interpolate like that. The Jiter just wont have any clue of the context or as to when to use that variable.

If you think it through, when should it replace it. On first use? What if you wanted to replace multiple Representations in different contexts, which scope should it consider. Sounds very unpredictable

However, if its an consolation. You could do this

public static string SetScore = "Score[@Set='{0}']";
...
result = string.Format(SetScore,currentSet)

Interpolated Strings (C# Reference)

Used to construct strings. An interpolated string looks like a template string that contains interpolated expressions. An interpolated string returns a string that replaces the interpolated expressions that it contains with their string representations.

Moreso

You can use an interpolated string anywhere you can use a string literal. The interpolated string is evaluated each time the code with the interpolated string executes. This allows you to separate the definition and evaluation of an interpolated string.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree this will work, I just want to see if somehow interpolate can work across classes.
alright, I give up. we cant do it. I have to use String.Format now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.