grmbl grmbl - 28 days ago 14
C# Question

When are interpolated string evaluated?

I have following code:

internal class Constants
{
internal static string Source { get; set; }

#region EvaluationRepository
internal static string QUERY_001 = $@"
select
e.*
from {Source} e
where
e.id = @Id
";

internal static string QUERY_002 = $@"
select
e.*
from {Source} e
where
e.statusid=@StatusId
and e.begindate >= @FromDate
and e.enddate <= @ToDate
";

internal static string QUERY_003
{
get
{
return $@"
select
d.statusid [StatusId],
count(1) [Count]
from
(select e.statusid
from {Source} e
where e.begindate >= @FromDate and e.enddate <= @ToDate) d
group by d.statusid
";
}
}
#endregion
}


The only time
{Source}
is filled is when I expose the query as a property. (QUERY_003)

It doesn't work when exposed as a field. (QUERY_001, QUERY_002)

Can anyone explain why? Because of the staticness (not sure if that's a word)?

Sorry for the verbatim interpolation noise for the SQL :)

Rob Rob
Answer

It's done at runtime. It's equivalent (down to the IL generated) to using string.Format.

The reason the fields are not properly filled is because Source is empty when it initially executes (when the static class is initialized).

Comments