2
// ConvertCastToAsAction.cs
5
// Mansheng Yang <lightyang0@gmail.com>
7
// Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com>
9
// Permission is hereby granted, free of charge, to any person obtaining a copy
10
// of this software and associated documentation files (the "Software"), to deal
11
// in the Software without restriction, including without limitation the rights
12
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
// copies of the Software, and to permit persons to whom the Software is
14
// furnished to do so, subject to the following conditions:
16
// The above copyright notice and this permission notice shall be included in
17
// all copies or substantial portions of the Software.
19
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27
using ICSharpCode.NRefactory.TypeSystem;
29
namespace ICSharpCode.NRefactory.CSharp.Refactoring
32
/// Converts a cast expression to an 'as' expression
34
[ContextAction ("Convert cast to 'as'.", Description = "Convert cast to 'as'.")]
35
public class ConvertCastToAsAction : SpecializedCodeAction<CastExpression>
37
static InsertParenthesesVisitor insertParentheses = new InsertParenthesesVisitor ();
38
protected override CodeAction GetAction (RefactoringContext context, CastExpression node)
40
if (node.Expression.Contains (context.Location))
42
// only works on reference and nullable types
43
var type = context.ResolveType (node.Type);
44
var typeDef = type.GetDefinition ();
45
var isNullable = typeDef != null && typeDef.KnownTypeCode == KnownTypeCode.NullableOfT;
46
if (type.IsReferenceType == true || isNullable) {
47
return new CodeAction (context.TranslateString ("Convert cast to 'as'"), script => {
48
var asExpr = new AsExpression (node.Expression.Clone (), node.Type.Clone ());
49
// if parent is an expression, clone parent and replace the case expression with asExpr,
50
// so that we can inset parentheses
51
var parentExpr = node.Parent.Clone () as Expression;
52
if (parentExpr != null) {
53
var castExpr = parentExpr.GetNodeContaining (node.StartLocation, node.EndLocation);
54
castExpr.ReplaceWith (asExpr);
55
parentExpr.AcceptVisitor (insertParentheses);
56
script.Replace (node.Parent, parentExpr);
58
script.Replace (node, asExpr);