using Foo.Uber;
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
// I want to reference the outer "absolute" Foo.Uber
// but the compiler thinks I'm refering to MyStuff.Foo.Uber
var x = Foo.Uber.Bar();
}
}
}
How could I solve this? Just moving the using statement inside my namespace doesn't help.
You can do this using a namespace alias qualifier (typically global::) to refer to the default / root namespace:
global::Foo.Uber
Alias the namespace in the using statement:
using ThatOuterFoo = Foo.Uber;
...
...
//Some time later...
var x = ThatOuterFoo.Bar();
You can use using alias directives
using Outer = Foo.Uber;
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
var x = new Outer.Bar(); //outer class
}
}
}
You can actually specify the full path via the root namespace
var x = global::Foo.Uber.Bar();
Namespaces Overview
A namespace has the following
properties:
They organize large code projects.
They are delimited with the . operator.
The using directive means you do not need to specify the name of the
namespace for every class.
The global namespace is the "root" namespace: global::system
will always refer to the .NET
Framework namespace System.
I prefer this over aliases because when you read it, you know exactly what is going on. Aliases can be easy to misunderstand if you skip over the definition.
Using Aliaseseseseseses
using Foo.Uber;
using FooUberBar = Foo.Uber.Bar
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
// I want to reference the outer "absolute" Foo.Uber
// but the compiler thinks I'm refering to MyStuff.Foo.Uber
var x = FooUberBar();
}
}
}
You can assign an alias in your using directive as described on MSDN.
Related
I have tried to search for this but every example I find has a problem like them actually having the same namespace as their class or something.
I am simply trying to start using Linq. When I add new item Host is localhost. I have my database in Visualstudio and my project name is different than the DataContext name but I can't get it initialized. I get error:
'LinkedContext' is a namespace but is used like a type'
here is code...
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedContext db = new LinkedContext();
}
}
}
LinkedContext doesn't work? In settings of the Database Diagram it says the Entity Namespace is 'LinkedContext' So what am I missing. I thought I saw you could run that one line of code to connect your database that is already in VisualStudio due to adding a new item and then start playing with it? I just want to be able to practice with a database! Do stuff like:
var example = from x in example.Table
orderby x.field
select x;
you need using LinkedContext at the top of your file. the error you’re getting is telling you LinkedContext is a namespace but you’re treating like a type, ie a class. once you define it at the top you can then use the type that you need within that namespace.
added "using LinkedContext" to the top of code then also had to use LinkedDataContext not just LinkedContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedContext;
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedDataContext db = new LinkedDataContext();
var example = from x in db.employees
orderby x.employee_id
select x;
foreach (var whatever in example)
{
Console.WriteLine(whatever.name);
}
When you hover over a "simplified" using directive in VS2015, it shows you the fully-qualified name. How would I get this information via a Roslyn plugin? Would it be using a DiagnosticAnalyzer? A CodeFixProvider?
Reading through source.roslyn.codeplex.com, there's tons of information there, including how to add a using statement, and also how to simplify type names (including using statements), but I'm unable to figure out how to go in reverse to get the fully-qualified name.
With the semantic model you can retrieve information about the semantics that make up your code (evidently) -- this allows you to get specific information about types and other constructs.
For example:
void Main()
{
var tree = CSharpSyntaxTree.ParseText(#"
using X = System.Text;
using Y = System;
using System.IO;
namespace ConsoleApplication1
{
}"
);
var mscorlib = PortableExecutableReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { tree }, references: new[] { mscorlib });
var semanticModel = compilation.GetSemanticModel(tree);
var root = tree.GetRoot();
// Get usings
foreach (var usingDirective in root.DescendantNodes().OfType<UsingDirectiveSyntax>())
{
var symbol = semanticModel.GetSymbolInfo(usingDirective.Name).Symbol;
var name = symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
name.Dump();
}
}
Output:
global::System.Text
global::System
global::System.IO
If you use SymbolDisplayFormat.CSharpErrorMessageFormat instead, you will receive
System.Text
System
System.IO
Your choice what you're interested in but as you can see it works just fine with aliases and without.
Here is my Enums.cs file that exists in a CPSLibrary Class Library:
namespace CPSLibrary.CPSEnums
{
public enum GoalType
{
STRATEGIC = 1,
TACTICAL = 2
}
}
In a code behind file within a web application that references CPSLibrary, I'm doing the following:
using CPSLibrary;
/* ... farther down the page ... */
proj.Goal == CPSLibrary.CPSEnums.GoalType.STRATEGIC;
That will work, but if I try to just reference it like CPSEnums.GoalType.STRATEGIC it won't. Additionally, if I add "using CPSLibary.CPSEnums" I can then reference it simply as GoalType.STRATEGIC.
What do I need to do to get this to recognize CPSEnums.GoalType.STRATEGIC ?
Oddly enough, other classes with the CPSLibrary Class Library can reference it as CPSEnums.GoalType.STRATEGIC just fine.
Bonus Question: in this example, does "CPSEnums" have a technical term? "Container" or something like that? Or is it just a part of the Namespace with no separate terminology?
TIA
Try changing your using statement to this...
using CPSEnums = CPSLibrary.CPSEnums;
This should allow you to reference it the way you want...
/* ... farther down the page ... */
proj.Goal == CPSEnums.GoalType.STRATEGIC;
Because your namespace name is CPSLibrary.CPSEnums, so you can even write like:
using CPSLibrary.CPSEnums;
....
proj.Goal == GoalType.STRATEGIC; //NO NAMESPACE NAME
when you write using CPSLibrary, you refer to the "parent" namespace of your defined one. This is perfectly valid. But to access your enum type, you need specify its namepsace, and its namespace is: CPSLibrary.CPSEnums
Try this:
namespace CPSLibrary
{
public static class CPSEnums
{
public enum GoalType
{
STRATEGIC = 1,
TACTICAL = 2
}
}
}
var x = CPSEnums.GoalType.STRATEGIC;
How can I add a namespace to a c# project? I am a beginner.
if(!string.IsNullOrEmpty(result))
{
CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);
EmailsList = helper.Extract_Emails;
}
My Form1 needs to use the namespace below:
// this is the file that I need to add
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Coderbuddy
{
public class ExtractEmails
{
private string s;
public ExtractEmails(string Text2Scrape)
{
this.s = Text2Scrape;
}
public string[] Extract_Emails()
{
string[] Email_List = new string[0];
Regex r = new Regex(#"[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}", RegexOptions.IgnoreCase);
Match m;
//Searching for the text that matches the above regular expression(which only matches email addresses)
for (m = r.Match(s); m.Success; m = m.NextMatch())
{
//This section here demonstartes Dynamic arrays
if (m.Value.Length > 0)
{
//Resize the array Email_List by incrementing it by 1, to save the next result
Array.Resize(ref Email_List, Email_List.Length + 1);
Email_List[Email_List.Length - 1] = m.Value;
}
}
return Email_List;
}
}
}
Well, add a using statement in your .cs page
using Coderbuddy;
Then your code can access the methods exposed by this type.
OR, put your winform .cs file in the same namespace (not a recommended idea)
Put this at the top of your code-behind file:
using Coderbuddy;
Read this introduction to namespaces and assemblies on MSDN.
(I am assuming you need to add that second file to your own project. If it is already part of another project in your solution, then add it as a project reference as Darkhydro has answered.)
You don't need to explicitly add namespaces to your project. The namespace declaration in line 6 of the file that you need to use does it implicity.
For this example, add a blank file called ExtractEmails.cs to your project (the convention if a file contains only one class definition is to name the file after the class), and then paste that code into it. Boom - namespace added :)
In your form code, you are already using the fully qualified name of the class (that is, you are mentioning the namespace in the line
CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);
so you don't need a "using" statement.
If you did add "using CoderBuddy;" to the top of your form's .cs file, then that line could change to
ExtractEmails helper = new ExtractEmails(result);
But in this case I would leave it as you already have it, because the namespace hints at the fact that the ExtractEmails code is slightly separated from the rest of your code.
The official tutorial from http://www.antlr.org/wiki/display/ST/Five+minute+Introduction doesn't work because of DefaultTemplateLexer, how to fix ?
using System;
using Antlr.StringTemplate;
class Script
{
static public void Main(string[] args)
{
StringTemplateGroup group = new StringTemplateGroup("myGroup", #"C:\Tutorials\stringtemplate", typeof(DefaultTemplateLexer));
StringTemplate helloAgain = group.GetInstanceOf("homepage");
helloAgain.SetAttribute("title", "Welcome To StringTemplate");
helloAgain.SetAttribute("name", "World");
helloAgain.SetAttribute("friends", "Terence");
helloAgain.SetAttribute("friends", "Kunle");
helloAgain.SetAttribute("friends", "Micheal");
helloAgain.SetAttribute("friends", "Marq");
Console.Out.WriteLine(helloAgain.ToString());
}
}
From the tutorial, you didn't include the using line:
using Antlr.StringTemplate.Language;
Which imports the namespace that DefaultTemplateLexer resides in. So either include that line or fully qualify the type.